80. Remove Duplicates from Sorted Array II
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.
解法一
相同元素的个数依次累加。注意从1开始。
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 && nums == null) {
return 0;
}
int i = 1, j = 1;
int count = 1;
while (j < nums.length) {
if (nums[j] != nums[j - 1]) {
count = 1;
nums[i++] = nums[j];
} else {
if (count < 2) {
nums[i++] = nums[j];
count++;
}
}
j++;
}
return i;
}
}
解法二
判断i-2元素是否小于该元素,小于就把该元素添加到数组里。
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int i = 0;
for (int num : nums) {
if (i < 2 || nums[i - 2] < num) {
nums[i++] = num;
}
}
return i;
}
}