Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.
Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn’t matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn’t matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
题目要求一个数字只能出现两次 超过两次则把他remove
非常巧妙的一个解法
定义变量 k,表示待修改的元素位置,默认为 0,然后遍历后面的元素判断符合条件时,覆盖 k,然后 k 向后移动一位。
判断条件为:
遍历的元素 n 不等于元素 k,也就代表不重复
遍历的元素 n 等于元素 k,但不等于 k - 1。则表示已经有两个重复元素了
对于第二点,需要注意,当 k = 0 时,没有 k - 1。
class Solution {
public int removeDuplicates(int[] nums) {
int k = 0;
for(int i =1;i < nums.length;i++){
if(nums[i] != nums[k] || k== 0|| (nums[i] == nums[k] && nums[i] != nums[k-1])){
//当前k为0 或 i位的数 != k位的数字 或等于且但不等于 k-1
nums[++k] = nums[i]; // k向前进一位并且赋值
}
}
return k+1;
}
}