Leetcode 80.刪除排序數組中的重複項 II

題目

給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素最多出現兩次,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 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 。你不需要考慮數組中超出新長度後面的元素。

代碼

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int length = nums.size();
        if(length==0) return 0;
        int countTime=1;
        int j=0;
        for(int i=1;i<length;i++)
        {
            if(nums[i]!=nums[j]){
                nums[++j]=nums[i];
                countTime=1;
            }else{
                if(++countTime<=2){
                    nums[++j]=nums[i];
                }
            }
        }
        return j+1;
    }
};

Leetcode 26很相似的題目,解題的思路也很像,區別就是添加一個變量countTime,這個變量記錄相同元素出現的次數。當出現次數不超過2次時,將其加入新數組中。

mark下Leetcode 題解上的答案,比我自己寫的好:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int length = nums.size();
        if(length<=2) return length;
        int index=2;
        for(int i=2;i<length;i++)
        {
            if(nums[i]!=nums[index-2])
                nums[index++] = nums[i];
        }
        return index;
    }
};

上述程序的運行結果:
在這裏插入圖片描述

參考資源:

Leetcode 80
Leetcode 題解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章