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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/two-pointer/26.-remove-duplicates-from-sorted-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
