1. Description
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
2. 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.
3. Code
public class LeetCode0080 {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int pre = 0;
int count = 1;
for(int i = 1; i< nums.length; i++) {
if(nums[i] == nums[pre]) {
if(count >= 2) {
continue;
}else {
count ++;
}
}else {
count = 1;
}
nums[++ pre] = nums[i];
}
return pre + 1;
}
public static void main(String[] args) {
LeetCode0080 leetcode = new LeetCode0080();
System.out.println(leetcode.removeDuplicates(new int[] {1,1,1,2,2,3}));
}
}
Comments | NOTHING