> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/two-pointer/26.-remove-duplicates-from-sorted-array.md).

# 26. Remove Duplicates from Sorted Array

![](/files/-MkwOaxL4H_0zRg1DelJ)

![](/files/-MkwOeRk4Z1pHMdzq2dp)

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;
    }
}
```
