题目:
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Hint:
1.Try two pointers.
2.Did you use the property of “the order of elements can be changed”?
3.What happens when the elements to remove are rare?
大意:
给定一个排序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,不要创建一个新的数组来保存结果。在常量内存空间解决这个问题 。
思路:
有两种解决方法,见代码注释。
代码:
public class Solution {
public int removeElement(int[] nums, int val) {
/*
//类似于26题的解决方法
int i = 0;
for(int j = 0; j < nums.length; j++) {
if(nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
*/
//定义两个标志位i,j,一个从最左侧开始(i),一个从最右侧开始(j)
//nums[i]的值为val时,将nums[j]的值赋给它,j--
//否则i++,判断下一个数组的值
int i = 0;
int j = nums.length - 1;
while(i <= j) {
if(nums[i] == val) {
nums[i] = nums[j];
j--;
} else {
i++;
}
}
return j + 1;
}
}