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.
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.
题意:
有序数组去重(允许某个元素重复出现两次)
思路:
仍然是在尽量不开新空间的情况下,直接在原数组中进行操作。(当然,我们可以想象另开了一个新的数组存储去重后的结果)
指针i来遍历原数组。
指针j 从 index 2 开始, 因为index 为 0、1 的元素是什么牛鬼蛇神都不重要。
指针j 接受指针i扫过的、符合条件的元素。
指针j所到之处,便是新“数组”新生之时。
代码:
class Solution {
public int removeDuplicates(int[] nums) {
// corner case
if(nums.length == 0 || nums == null) return 0;
int j = 2;
for(int i = 2; i < nums.length; i++){
if(nums[i] != nums[j-2]){
nums[j] = nums[i];
j++;
}
}
return j;
}
}