C++ O(1) space (2 ints), O(n) runtime (80 percentile), 5 lines, straightforward


  • 0
    J
    int removeDuplicates(vector<int>& nums) {
        int front = 0;
        for(int i = 0; i < nums.size(); ++i) {
            while(nums[i+1] == nums[i]) {++i;}
            nums[front++] = nums[i];
        }
        return front;
    }
    

    It runs through the vector and grabs the last one in any given run of numbers.

    Luckily, it didn't have to deal with out-of-bounds errors, but a quick check and return if EOF is sufficient


  • 0
    H

    you need check i+1 should be lower than nums.size()-1. otherwise it maybe compile error.


  • 0
    M

    @huijun operator[] in vector<T> won't check the bound


  • 0
    H

    @miao100tw i mean u need to add the check otherwise it gonna be compile error. u can run again to see what happens.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.