---
# System prepended metadata

title: 26.Remove Duplicates from Sorted Array
tags: [Leetcode, '2021']

---

---
title: 26.Remove Duplicates from Sorted Array
tags: Leetcode,2021
---
# 【LeetCode】26. Remove Duplicates from Sorted Array
## Description
>Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

>給一個已經排序完的陣列nums，用in-place演算法移除重複的元素，使每個元素都只會出現一次，並回傳新的長度。
不要去分配額外的空間給其他陣列，你應該直接修改輸入的陣列，空間複雜度應為O(1)。

## Example:
```
Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.


Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],
```

>Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

>It doesn't matter what values are set beyond the returned length.
## Solution
<!-- >紀錄第一個元素在temp。
遍歷陣列，如果和temp一樣，就移除；否則將temp更新。
其他注意：用nums.size()的速度很慢，你可以另外用一個空間去儲存、操作它。
其他注意：用這個Code跑LeetCode的速度會輸給超多人，原因是其他人沒有使用in-place演算法，但評測程式不會抓。 -->
## Code
```
public class Solution {
    public int RemoveDuplicates(int[] nums)
    {
        if (nums.Length == 0)
            return 0;

        int i = 0;
        for(int j = 1; j < nums.Length; j++)
        {
            if (nums[i] != nums[j])
            {
                nums[i++ + 1] = nums[j];
            }
        }

        return ++i;
    }
}
```
