26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once 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 of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

S: read write pointer

    int removeDuplicates(vector<int>& nums) {
        int w = 0;
        for (int i : nums) {
            if (w < 1 || i != nums[w - 1]) {
                nums[w++] = i;
            }
        }
        return w;
    }

80. Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at mosttwice?

For example,
Given sorted arraynums=[1,1,1,2,2,3],

Your function should return length =5, with the first five elements ofnumsbeing1,1,2,2and3. It doesn't matter what you leave beyond the new length.

S: read write pointer

因为允许出现两次,比较read ponter和writer pointer前两位num的值即可

    int removeDuplicates(vector<int>& nums) {
        int w = 0;
        for (int i : nums) {
            if (w < 2 || i != nums[w - 2]) {
                nums[w] = i;
                w++;
            }
        }
        return w;
    }

results matching ""

    No results matching ""