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.
方法一:Runtime: 2 ms beats 6.90% of javasubmissions.
public int removeDuplicates(int[] nums) {
int count = 0, j;
for (int i = 0; i < nums.length; ) {
int now = nums[i];
for (j = i; j < nums.length; j++) {
if (nums[j] != now) break;
if (j - i < 2) nums[count++] = now;
}
i = j;
}
return count;
}
方法二: Runtime: 1 ms beats 59.44% of javasubmissions.
public int removeDuplicates3(int[] nums) {
if (nums.length <= 1) return nums.length;
int index = 2;//新数组下标
for (int i = 2; i < nums.length; i++)
if (nums[i] != nums[index - 2]) nums[index++] = nums[i];
return index;
}