Remove Duplicates from Sorted Array
Tags: algorithms, csharp, leetcode, easy
Published: 2022-10-06 01:49:24

_#26.Remove Duplicates from Sorted Array_

### Problem statement
Given an integer array `nums` sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.

Return `k` after placing the final result in the first `k` slots of `nums`.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

__Custom Judge:__

The judge will test your solution with the following code:

```
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}
```

If all assertions pass, then your solution will be __accepted__.

**Example 1**
```
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
```

**Example 2**
```
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
```

### Explanation
給定一個遞增排序的整數陣列，我們必須就地刪除重複的項目，使得每個元素只出現一次，而元素對應的順序需保持不變，返回剩餘元素的數量（經由測試，我猜測應該是返回剩餘元素數量，如果有誤還請告知）

限制只能使用額外的 O(1) 的記憶體空間，另外，因為某些語言宣告陣列後無法改變其長度，所以最終檢查時只會檢查前半段結果的部分，而陣列後半段非結果的部分不會檢查，可任意留下任何值，題目也附上如何檢查陣列的程式碼，它僅僅只檢查到我們要返回的結果值以前的元素

### Solution
題目蠻簡單的，如果只是刪除重複元素作法不只一種，不過題目限制只能使用 O(1) 的額外空間，不能額外建立一個陣列來儲存元素，那麼只能直接遍歷題目給的陣列，並改變其陣列內的值，建立一個 `int` 變數來計數不重複元素的個數

迴圈從 1 開始，將 `nums[res]` 和 `nums[i]` 比較是否相同，此處比較的元素即索引 0 和 索引 1 元素，故迴圈不從 0 開始，比較後兩值不相同就讓 res+1，將 `nums[i]` 指給 `nums[res]` ，如果相同則繼續迴圈，最後返回 res+1，因為 res 是從 0 開始，最後必須加上 1 讓它等於元素的個數 

```cs
public int RemoveDuplicates(int[] nums)
{
    if (nums.Length == 0) return 0;

    int res = 0;

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

    return ++res;
}
```

或者再精簡一點的寫法，移除 ++res，並將 nums[res] 替換成 nums[++res]，運作的方式相同，先執行增量再存取 res 索引

```csharp
public int RemoveDuplicates(int[] nums)
{
    if (nums.Length == 0) return 0;

    int res = 0;

    for (int i = 1; i < nums.Length; i++)
        if (nums[res] != nums[i])
            nums[++res] = nums[i]; // shorter writing.

    return ++res;
}
```

### Reference
[LeetCode Solution](https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/1326107/C-Solution)

[GitHub Repository](https://github.com/FakeStandard/LeetCode-CSharp/tree/main/Solution/0026.Remove-duplicates-from-sorted-array)

---

Thanks for reading the article :tulip: :sunflower: :blossom:

If you like it, please don't hesitate to click heart button :heart:
or click like on my Leetcode solution
or follow my [GitHub](https://github.com/FakeStandard) :star:
or buy me a coffee :arrow_down: I'd appreciate it.

[![Buy-me-a-coffee][1]][2]

[1]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h077sxd0vx1hix4t7lw8.png
[2]: https://www.buymeacoffee.com/FakeStandard

---