题目描述
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 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
思路
- 双指针思路,使用一个慢指针和一个快指针,快指针
j用来寻找不等于val的值,慢指针i负责索引位置,等待接收j指向的值,i同时也表示数组中不等于val的个数 - 本题思路与下面这题极其相似,可以参考一下
Leetcode–Java–26. Remove Duplicates from Sorted Array
代码
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0; //即作为索引,也表示不等于val的值的个数
for (int j = 0; j < nums.length; j++){
//j指向的值等于val就不断往后走,直到指向的不等于val,然后调整归位
if (nums[j] != val){
nums[i] = nums[j];
i ++;
}
}
return i;
}
}
本文介绍了一种在原地移除数组中特定值并返回新长度的算法。通过双指针技巧实现,快指针搜索非目标值,慢指针记录有效元素。适用于数值处理与数组操作场景。
387

被折叠的 条评论
为什么被折叠?



