lintcode-easy-Remove Duplicates from Sorted Array II
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]
.
按理说不太难,但是做过的题有时候还是一下写不对……
分情况讨论:
当重复个数只有1个的时候,如果j对应的数是重复的,重复个数count加1
当重复个数为2的时候,找到下一个不重复的数,加到末尾
public class Solution { /** * @param A: a array of integers * @return : return an integer */ public int removeDuplicates(int[] nums) { // write your code here if(nums == null) return 0; if(nums.length <= 2) return nums.length; int i = 1; int j = 1; int count = 1; while(j < nums.length){ if(count == 1){ if(nums[j] == nums[j - 1]){ count++; nums[i] = nums[j]; i++; j++; } else{ nums[i] = nums[j]; i++; j++; } } else{ while(j < nums.length && nums[j] == nums[j - 1]) j++; if(j < nums.length){ nums[i] = nums[j]; count = 1; i++; j++; } } } return i; } }