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 1
, 1
, 2
, 2
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 来记录出现重复数字的次数
1 public class Solution 2 { 3 public int removeDuplicates(int[] nums) 4 { 5 if(nums.length <= 2) 6 return nums.length; 7 8 int pointer = 0; 9 int count = 1; 10 11 for(int i=1; i<nums.length; i++) 12 { 13 // if this number is different than pointer number 14 if(nums[i] != nums[pointer]) 15 { 16 pointer++; 17 nums[pointer] = nums[i]; 18 count = 1; 19 } 20 else // if this number is same as pointer number 21 { 22 if(count == 1) // if it is second same number 23 { 24 pointer++; 25 nums[pointer] = nums[i]; 26 count++; 27 } 28 } 29 } 30 31 return pointer + 1; 32 } 33 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List