Simple C++ O(n) solution

  • 15
    int removeDuplicates(vector<int>& nums) {
        int pos = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (i == 0 || nums[i] != nums[pos - 1])
                nums[pos++] = nums[i];
        return pos;

  • 1

    title is : Remove Duplicates from Sorted Array!
    But you do not delete duplicate element , and the array is confused!so how do you accepted?

  • 1

    Please note this in the problem: It doesn't matter what you leave beyond the new length.
    So we just need to put all the unique elements into nums[0:pos].
    It's all right to have duplicate elements in nums[pos:].

  • 0

    I actually deleted the duplicate element, and I'm pretty sure I have passed the necessary test cases, but the output is always empty.

Log in to reply

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