---
# System prepended metadata

title: 26. Remove Duplicates from Sorted Array
tags: [leetcode, array]

---

# 26. Remove Duplicates from Sorted Array

題目：<https://leetcode.com/problems/remove-duplicates-from-sorted-array/>

解法：採用直接解，python依序找出重複值的element使用pop(i)移除，c則是依序從找出不同值的element後移動到正確位置

Python3：

``` python 3
class Solution:
    def removeDuplicates(self, nums: list[int]) -> int:
        i = 0
        while i < len(nums) - 1:
            if nums[i] == nums[i + 1]:
                nums.pop(i)
            else:
                i += 1
        return len(nums)

if __name__ == '__main__':
    nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]

    ans = Solution().removeDuplicates(nums)

    print(nums)
    print(ans)
```

C：

``` c
#include <stdio.h>
#include <stdlib.h>

int removeDuplicates(int* nums, int numsSize){
    int k = 0;
    for (int i = 0; i < numsSize; i++)
        if (nums[i] != nums[k]) {
            nums[++k] = nums[i];
        }
    return ++k;
}

int main()
{
    int nums[] = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    
    int ans = removeDuplicates(nums, numsSize);
    
    for (int i = 0; i < numsSize; i++)
        printf("%d ", nums[i]);
    printf("\n");
    printf("%d\n", ans);
    
    return 0;
}
```

###### tags: `leetcode` `array`
