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.
public class Solution {
public int removeDuplicates(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int index = 0;
for(int i = 0; i < nums.length; i++){
if (!map.containsKey(nums[i])){
map.put(nums[i],1);
nums[index] = nums[i];
index++;
}
else if(map.get(nums[i]) < 2){
map.put(nums[i], map.get(nums[i])+1);
nums[index] = nums[i];
index++;
}
else{
continue;
}
}
return index;
}
}
比较顺利。bug free。 题目简单。时间复杂度O(n).