题目描述
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
nums
= [3,2,2,3]
val
= 3,
return length = 2, with the first two elements of nums being 2.
就是原地删除值为val的数组元素,空间复杂度限定为O(1),不允许开辟新数组
分析
简单题, 使用双指针,初始化两个指针i 和 j 在数组头部, 并且 j 比 i 移动的快。
如果 j 指针指向的元素不等于 val, 那么就用 j 指针位置的值复制到 i 指针上, 将 i 指针和 j 指针同时移动到下一位。
如果 j 等于 val, j 指针向右移动一位跳过当前元素
Javascript
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let i = 0
for (let j = 0; j < nums.length; j++) {
// nums[j]为所给值, 什么都不做,j 向右跳一位
if (nums[j] === val) {
continue
}
// nums[j]不等于val时,把mums[j]复制到nums[i], i 和 j 同时向右走一位
nums[i++] = nums[j]
}
return i
};
This post has received a 3.13 % upvote from @drotto thanks to: @hughie8.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit