# 26. Remove Duplicates from Sorted Array

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mkw9TIr13Afg-k4D_Eb%2F-MkwOaxL4H_0zRg1DelJ%2Fimage.png?alt=media\&token=d9115e20-2f54-41a4-8b4c-2e93e71166ec)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mkw9TIr13Afg-k4D_Eb%2F-MkwOeRk4Z1pHMdzq2dp%2Fimage.png?alt=media\&token=7c5705eb-8b0f-48b2-88db-08d8813939a8)

time: O(n)

space: O(1)

```java
class Solution {
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
        int i, j = 1;
        for (i = 0; i < n ; i++) {
            while (j < n && nums[j] == nums[i]) {
                j++;
            }      
            if (j == n) {
                break;
            }
            nums[i+1] = nums[j];
        }
        return i+1;
    }
}

/*
[0,1,2,3,4,2,2,3,3,4]
                   j        
         i
         
         so the ans is i+1
*/
```



## more easier way

because when number are different, set number to front, so...

&#x20;這的 i, 就像上一個做法的 j, count 就像上一個做法的 i

```java
class Solution {
    public int removeDuplicates(int[] nums) {
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i-1] != nums[i]) {
                nums[count++] = nums[i];
            }
        }
        return count;
    }
}
```
