【LeetCodeゼロブラシから】Remove Duplicates from Sorted ArrayI&II


Iテーマ:
Given a sorted array, remove the duplicates in place such that each element appear onlyonce and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array nums = [1,1,2] ,
Your function should return length = 2 , with the first two elements ofnums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
回答:
2つのポインタ:curとpreを設計します.preは正常に遍歴し,curは更新後の配列を記録する境界である.
注意:私のやり方は、現在の要素と次の要素を比較することです.そのため、最後の要素は個別に比較し、処理する必要があります.
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int size = nums.size();
        if(size == 0)   return 0;
        if(size == 1)   return 1;
        
        int cur = 0;
        int pre = 0;
        for(; pre< size - 1; pre++)
        {
            if(nums[pre] != nums[pre + 1])
            {
                nums[cur] = nums[pre];
                cur ++;
            }
            else
                nums[cur] = nums[pre];
        }
        if (nums[pre] != nums[cur])
            nums[cur] = nums[pre];
        return cur + 1;
    }
};

IIタイトル:
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 ofnums being 1 , 1 , 2 , 2 and 3 . It doesn't matter what you leave beyond the new length.
回答:
前の問題と同じ理屈だ.ただ今回はcountを増やし、現在何回目か前の要素を繰り返したことを記録します.また、最後の要素に注意してください.
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int count = 0;
        int size = nums.size();
        if (size <= 2)  return size;
        
        int cur = 0;
        int pre = 0;
        for (; pre<size - 1; pre++) {
            if(nums[pre] != nums[pre + 1]) {
                if(count <= 1) {
                    nums[cur] = nums[pre];
                    cur++;
                } 
                count = 0;
            }
            else if (nums[pre] == nums[pre + 1] && count <= 1) {
                nums[cur] = nums[pre];
                cur++;
                count++;
            }
        }
        
        if(count <= 1) {
            nums[cur] = nums[size - 1];
            cur++;
        }
        return cur;
    }
};