1. 程式人生 > >LeetCode 80. 刪除排序數組中的重復項 II(Remove Duplicates from Sorted Array II)

LeetCode 80. 刪除排序數組中的重復項 II(Remove Duplicates from Sorted Array II)

div 16px return aid clas 函數返回 == pre 拷貝

題目描述

給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素最多出現兩次,返回移除後數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。

示例 1:

給定 nums = [1,1,1,2,2,3],

函數應返回新長度 length = 5, 並且原數組的前五個元素被修改為 1, 1, 2, 2, 3 。

你不需要考慮數組中超出新長度後面的元素。

示例 2:

給定 nums = [0,0,1,1,1,1,2,3,3],

函數應返回新長度 length = 7, 並且原數組的前五個元素被修改為 0, 0, 1, 1, 2, 3, 3 。
你不需要考慮數組中超出新長度後面的元素。

說明:

為什麽返回數值是整數,但輸出的答案是數組呢?

請註意,輸入數組是以“引用”方式傳遞的,這意味著在函數裏修改輸入數組對於調用者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);

// 在函數裏修改輸入數組對於調用者是可見的。
// 根據你的函數返回的長度, 它會打印出數組中該長度範圍內的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解題思路

雙指針法,維護左指針和右指針,其中右指針指向左指針後第二個數或是緊鄰之後的不同數字。若找到大於兩個的重復數字,刪除右指針指向的數字知道右指針指向數字與左指針不同。註意在刪除數時更新數組長度減一。

代碼

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         int size = nums.size();
 5         int left = 0, right = 1;
 6         while(right < size){
 7             while(nums[left] == nums[right] && right - left < 2)
 8                 right++;
9 while(nums[left] == nums[right] && right < size){ 10 vector<int>::iterator iter = nums.begin() + right; 11 nums.erase(iter); 12 size--; 13 } 14 left = right; 15 right++; 16 } 17 return size; 18 } 19 };

LeetCode 80. 刪除排序數組中的重復項 II(Remove Duplicates from Sorted Array II)