My Solution : Time O(n), Space O(1)

• ``````class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n < 2) return n;
int id = 1;
for(int i = 1; i < n; ++i)
if(A[i] != A[i-1]) A[id++] = A[i];
return id;
}
};``````

• Pay attention to "Writing code? Select all code block then click on the {} button to preserve code formatting.” above text editor.

• Thanks for attention.

• Can you explain the algorithm? I am bit confused with ++i and id++ bits as I am trying to implement it in python. Python does not allow ++ operators.

Any help is appreciated.

• (++i) means to add 1 to i itself and return the new value
(id++) means to add 1 to id itself and return the old value

• can you explain what happens if all the numbers are same?
for ex : A = [2,2,2] then from your code id remains as 1 which is true but array doesn't get changed right???
correct me if i am wrong.

• OP's idea is similar to this problem
https://oj.leetcode.com/problems/remove-element/
the only difference is comparing two adjacent elements in array rather than given element.

• Simple and understandable

• General method to do it! Bravo!

• just count how many different numbers there are in the array, and place the n-th number in the n-th place of the array, in which id represents n.

• I'm not understanding why this code should work. For example the input is [1, 2, 3]. Then in the first loop, id points to 2, and i points to 3, it would replace 2 with 3, which is not correct behavior. Where did I get wrong about this code?

• may be change name id to index, you will feel much easier to understand.

• sorted array, dude~

• the input should be sorted

• it's not a sort array,isn't it?

• {0,1,2,0}, it does not compare the whole elements

• sorry, please re-read the question, "each element appear only once "

• This post is deleted!

• i think the methon is prefect right.. what'is wrong whit it?

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