80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array II_第1张图片
class Solution {
public:
    int removeDuplicates(vector& nums) {
        if(nums.size() == 0)
            return 0;
        int cur_index = 1;
        int cur_num = nums[0];
        bool flag = 1;
        for(int i = 1;i < nums.size();i++){
            if(nums[i] == cur_num && flag){
                flag = 0;
                nums[cur_index] = nums[i];
                cur_index++;
            }
            else if(nums[i] != cur_num){
                cur_num = nums[i];
                nums[cur_index] = cur_num;
                cur_index++;
                flag = 1;
            }
            else{
                continue;
            }
        }
        return cur_index;
    }
};

解法二

注意 是nums[index-2]

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

你可能感兴趣的:(80. Remove Duplicates from Sorted Array II)