Remove Duplicates from Sorted Array II
Description
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice ?
EXAMPLE:
Given sorted array nums = [1,1,1,2,2,3], Return length of the new array = 5, an array of [1, 1, 2, 2, 3].
Solution 1.
Since the array is sorted, the same elements must lay next to each other.
Add a variable to count the time that an element appears.
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int j = 0;
int cnt = 0;
for(int i = 1; i < nums.length; i ++) {
if (nums[i] != nums[j]) {
nums[++j] = nums[i];
cnt = 0;
} else {
cnt ++;
if (cnt < 2) {
nums[++j] = nums[i];
}
}
}
return j++;
}
}
Solution 2. Easy Lines...
.......
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}