LeetCode Problem
80. Remove Duplicates from Sorted Array II
Link to LeetCode
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].
Analysis
So this problem also requires in-place array manipulation.
public int removeDuplicates(int[] nums) {
if(nums==null){
return 0;
}
if (nums.length <= 2){
return nums.length;
}
/*
1,1,1,2,2,3
i j
*/
int i = 1; // point to previous
int j = 2; // point to current
while (j < nums.length) {
if (nums[j] == nums[i] && nums[j] == nums[i - 1]) {
j++;
} else {
i++;
nums[i] = nums[j];
j++;
}
}
return i + 1;
}
class Solution {
// #Not my algo
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i - 2])
nums[i++] = n;
return i;
}
/* for 0 dublicate allowed
public int removeDuplicates(int[] nums) {
int i = 0;
for(int n : nums)
if(i < 1 || n > nums[i - 1])
nums[i++] = n;
return i;
}
*/
}