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]);
}
解法一
遍历数组,用cur表示当前位置,pre表示遍历的数组位置,count计算当前数字出现了几次。这段代码思路不够清晰,建议直接看解法二,解法一仅作记录。
public int removeDuplicates(int[] nums) {
if(nums==null||nums.length==0)
return 0;
int pre=1,cur=1,count=1;
while(pre<nums.length)
{
while(pre<nums.length&&count<2)
{
if(pre<nums.length&&nums[pre]==nums[pre-1])
{
nums[cur++]=nums[pre++];
count++;
}
else
{
nums[cur++]=nums[pre++];
count=1;
}
}
while(pre<nums.length&&nums[pre]==nums[pre-1])
{
pre++;
}
count=1;
}
return cur;
}
Runtime: 6 ms, faster than 63.06% of Java online submissions for Remove Duplicates from Sorted Array II.
Memory Usage: 40.4 MB, less than 24.27% of Java online submissions for Remove Duplicates from Sorted Array II.
解法二
与解法一类似但代码更清晰,用count记录重复个数,如果出现了一个重复的则减1,如果count=0了说明已经有两个重复的数字了,后面的重复数字跳过
public int removeDuplicates(int[] nums) {
if(nums.length<=2)
return nums.length;
int cur=0,pre=1,count=1;
while(pre<nums.length)
{
if(nums[cur]==nums[pre]&&count==0)
++pre;
else
{
if(nums[cur]==nums[pre])
--count;
else
count=1;
nums[++cur]=nums[pre++];
}
}
return cur+1;
}
Runtime: 5 ms, faster than 99.97% of Java online submissions for Remove Duplicates from Sorted Array II.
Memory Usage: 40.1 MB, less than 29.54% of Java online submissions for Remove Duplicates from Sorted Array II.
解法三
在中文版leetcode评论区看到的一段代码,非常简练,很厉害。
遍历nums中的数字,用i记录当前数字重复了多少次,如果重复不超过两次或者当前数与前前个数不相等,则记录,不满足条件则跳过这个数。
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
Runtime: 5 ms, faster than 99.97% of Java online submissions for Remove Duplicates from Sorted Array II.
Memory Usage: 40.3 MB, less than 26.11% of Java online submissions for Remove Duplicates from Sorted Array II.