給你一個有序數組 nums ,請你 原地 刪除重復出現的元素,使每個元素 最多出現兩次 ,返回刪除后數組的新長度。
不要使用額外的數組空間,你必須在 原地 修改輸入數組 并在使用 O(1) 額外空間的條件下完成。
思路:
雙指針
count記錄重復了幾次
class Solution {public int removeDuplicates(int[] nums) {int slow = 0;int count = 0;for(int fast = 1;fast<nums.length;fast++){if(nums[fast]>nums[fast-1]){//判斷是否出現重復nums[++slow] = nums[fast];count = (count==0)?0:0;//將上次記錄清零}else{count++;if(count<2)//只有重復一次時可以加入nums[++slow] = nums[fast];}}return (slow+1);}
}