Friday, July 10, 2015

Leetcode 80: remove duplicates from sorted arrayII

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 of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.


remove duplicates, left 2 elements, 0-slow: done element, slow-fast: unknown, fast-size: explore

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        //sanity check
        if (nums.size() <= 2) return nums.size();
        int slow = 2;
        int fast = slow;
        for (; fast < nums.size(); fast++) {
            if (nums[fast] != nums[slow-2]) {
                nums[slow] = nums[fast];
                slow++;
            }
        }
        return slow;
    }
};

No comments:

Post a Comment