LeetCode 80. Remove Duplicates from Sorted Array II (从有序序列里移除重复项之二)

时间:2021-11-03 21:43:54

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.


题目标签:Array
  这道题目和之前的区别就是,可以保留第二个重复的数字。基本想法都和前一题一样,在这里只要多加一个int count 来记录这是第几个重复的number,如果是第二个的话,把pointer 往右移动一格,并且把nums[i] 的值 复制到 nums[pointer],然后count++。除此之外,还需要在遇到不同数字的情况里,加上,count = 1, 因为一旦遇到不同的数字,那么count 计数又要重新开始了。详细可以看代码,和之前那题代码的比较。
 
 
 

Java Solution:

Runtime beats 27.80%

完成日期:07/29/2017

关键词:Array

关键点:多设一个int count 来记录出现重复数字的次数

 public class Solution
{
public int removeDuplicates(int[] nums)
{
if(nums.length <= 2)
return nums.length; int pointer = 0;
int count = 1; for(int i=1; i<nums.length; i++)
{
// if this number is different than pointer number
if(nums[i] != nums[pointer])
{
pointer++;
nums[pointer] = nums[i];
count = 1;
}
else // if this number is same as pointer number
{
if(count == 1) // if it is second same number
{
pointer++;
nums[pointer] = nums[i];
count++;
}
}
} return pointer + 1;
}
}

参考资料:N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List