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.
Related issue: 26 Remove Duplicates from Sorted Array
public class Solution {
public int removeDuplicates(int[] nums) {
int i=0;
int j=1;
boolean allowDup = true;
for(;j<nums.length;){
if(nums[i] == nums[j]){
if(allowDup){
allowDup = false;
nums[++i] = nums[j++];
}else{
j++;
}
}else{
allowDup = true;
nums[++i] = nums[j++];
}
}
return ++i;
}
}
slightly simpler code.
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null) return 0;
if(nums.length <= 2) return nums.length;
boolean allow = true;
int l = 0;
for(int r=1; r<nums.length; r++){
if(nums[r] == nums[l]){
if(allow){
nums[++l] = nums[r];
allow = false;
}
}else{// not equal case.
allow = true;
nums[++l] = nums[r];
}
}
return l+1;
}
}
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null) return 0;
if(nums.length <= 2) return nums.length;
boolean allow = true;
int k = 0;
for(int i =1 ; i< nums.length; i++){
if(nums[i] != nums[k] || allow){
nums[++k] = nums[i];
allow = nums[i] != nums[k-1] ? true : false;
}
}
return ++k;
}
}