題目
跟進(jìn)“刪除重復(fù)數(shù)字”:
如果可以允許出現(xiàn)兩次重復(fù)將如何處理?
樣例給出數(shù)組A =[1,1,1,2,2,3],你的函數(shù)應(yīng)該返回長度5,此時A=[1,1,2,2,3]。
分析
這是上一篇刪除數(shù)組中重復(fù)元素的加強(qiáng)版,顯然主要思路是不變的,為了控制重復(fù)出現(xiàn)的次數(shù)的話,顯然需要設(shè)置一個變量來記錄重復(fù)的次數(shù),然后根據(jù)這個變量的值來判斷是否保留或者刪除。
代碼
public class Solution {
/**
* @param A: a array of integers
* @return : return an integer
*/
public int removeDuplicates(int[] nums) {
// write your code here
if(nums.length == 0) return 0;
int fast;
int slow = 1;
int count = 0;
for(fast = 1; fast < nums.length; ++fast)
{
if(nums[fast] == nums[slow-1])
{
count++;
if(count>=2)
continue;
}
else
count = 0;
nums[slow] = nums[fast];
slow++;
}
return slow;
}
}