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.
思路:参考remove duplicates,一样的跳过,不一样的存index。这个就是三次和三次以上的跳过,用map来记录次数即可,想法是一样的。不一样的直接存,一样的判断次数是不是大于二次,大于二次跳过,不是的话就存。
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length<=2){ return nums.length; } Map<Integer,Integer> check=new HashMap<Integer,Integer>(); check.put(nums[0],1); int index=1; for(int i=1;i<nums.length;i++){ if(nums[i]!=nums[i-1]){ nums[index++]=nums[i]; check.put(nums[i],1); }else{ if(check.get(nums[i])<2){ nums[index++]=nums[i]; check.put(nums[i],check.get(nums[i])+1); } } } return index; } }