問題:
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.
這個問題相對而言比較簡單,在紙上畫1下處理進程便可。
代碼示例:
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int begin = 0;
int end = 1;
//記錄同1個字符重復的次數(shù)
int count = 1;
while (end < nums.length) {
//end與begin對應數(shù)1致時
if (nums[end] == nums[begin]) {
//更新count
++count;
//count <= 2時,將end移動到begin后1個位置,同時增加begin
//否則,數(shù)量過量,不移動begin,直到找到下1個不1樣的數(shù)
if (count <= 2) {
nums[begin+1] = nums[end];
++begin;
}
} else {
//找到不1樣的數(shù),將end移動到begin后1個位置,同時增加begin
count = 1;
nums[begin+1] = nums[end];
++begin;
}
++end;
}
return begin+1;
}
}