标签:
题目:
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]
.
题解:
之前是不允许有重复的。
现在是可以最多允许2个一样的元素。
然后删除duplicate,返回长度。
删除duplicate的方法就是指针的操作。具体方法见代码。
public int removeDuplicates(int[] nums) { int n=nums.length; int prev=1; int curr=2; if (n<=2) return n; while(curr<n) { if(nums[curr]==nums[prev]&&nums[curr]==nums[prev-1]) curr++; else { prev++; nums[prev]=nums[curr]; curr++; } } return prev+1; }
Reference: http://www.programcreek.com/2013/01/leetcode-remove-duplicates-from-sorted-array-ii-java/
*Remove Duplicates from Sorted Array II
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4555992.html