题目:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
分析:题意是要求从给定的数组中移除给定元素。
改题简单,基本思路是:直接将除给定元素外其他元素直接放到新的数组(泛型)里,直接一个for循环加判断就可以解决。
java代码: Accepted
//Special case
if(nums == null || nums.length == 0)
return 0;
//Normal case
for(int i = 0;i < nums.length;i ++){
if(val != nums[i]){
list.add(nums[i]);
}
}
for(int i = 0;i < list.size();i ++){
nums[i] = list.get(i);
}
return list.size();
上述方法很直接,但是如果题意要求不能新开空间,那么如何做呢?
基本思路,在原来的数组上做文章,将给定元素直接移除,把其他元素直接覆盖到给定元素的位置,重构数组。如图示意:
利用“双指针”i,j,i指向“新数组”的序号,j用于寻找不等于给定元素的元素,当遇到非给定元素是“指针”i,j同时移动,否则,只有j移动,直到遍历最后。
Java代码: Acdepted
public class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int j = 0;
while(j < nums.length){
if(nums[j] != val){
nums[i] = nums[j];
i ++;
}
j ++;
}
//System.out.println(Arrays.toString(nums));
return i;
}
}

本文介绍了一种在数组中移除特定值并返回新长度的算法。提供了两种解决方案:一种使用额外空间存放新数组;另一种则是在原数组上进行操作,通过双指针技巧实现高效元素移除。

620

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



