https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
解题思路:
与Remove Duplicates from Sorted Array相比,这道题稍微复杂点。因为要求一个数字最多可以出现两次,很容易想到在上题的基础上,加入一个变量计数。i作为遍历游标,遇到比record大的数字时,操作不变,同时将count重置为1。区别就是,遇到和record相等的数字,原来是不需要操作的,这里首先count必须++。其次,如果在++前,count<2,那么还需要把当前数字和swapIndex的数字交换位置,同时swapIndex++。这种情况下的swap开始忘记了,导致程序一直出错。
同样,不swap,直接A[swapIndex] = A[i],也是可以的。
public class Solution { public int removeDuplicates(int[] A) { if(A.length == 0){ return 0; } int swapIndex = 1; int count = 1; int record = A[0]; for(int i = 1; i < A.length; i++){ if(A[i] == record){ if(count < 2){ int temp = A[swapIndex]; A[swapIndex] = A[i]; A[i] = temp; swapIndex++; } count++; } if(A[i] > record){ record = A[i]; // if(count > 2){ int temp = A[swapIndex]; A[swapIndex] = A[i]; A[i] = temp; // } swapIndex++; count = 1; } } return swapIndex; } }
update 2015/05/20:
二刷。压根就不要看大小,大小只用来计算出现的次数。只要次数<=2的,都要甩到前面去。
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0) { return 0; } int len = 1, count = 1, pre = nums[0]; for(int i = 1; i < nums.length; i++) { if(nums[i] == pre) { count++; } else { count = 1; pre = nums[i]; } if(count <= 2) { nums[len] = nums[i]; len++; } } return len; } }