###### tags: `Leetcode` `easy` `pointer` `python` `c++`
# 26. Remove Duplicates from Sorted Array
(此題倒讚異常多...但還是解來練習)

## [題目來源:] https://leetcode.com/problems/remove-duplicates-from-sorted-array/
## 題目:
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
## 解題想法:
使用兩pointer head、tail
看代碼自己trace幾次~
## Python:
``` python=
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
head=0
tail=1
while tail<len(nums):
if nums[head]==nums[tail]:
tail+=1
else: #遇到不同了 可以取代
head+=1
nums[head]=nums[tail]
return head+1
if __name__ == '__main__':
result = Solution()
nums = [0,0,1,1,1,2,2,3,3,4]
ans = result.removeDuplicates(nums)
print(ans)
```
## C++:
``` cpp=
// #include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int removeDuplicates(vector<int> &nums)
{
int head = 0;
int tail = 1;
while (tail < nums.size())
{
if (nums[head] == nums[tail])
tail += 1;
else
{
head += 1;
nums[head] = nums[tail];
}
}
return head += 1;
}
};
int main()
{
Solution res;
vector<int> nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int ans = res.removeDuplicates(nums);
cout << "After remove duplicates nums len: " << ans << endl;
for (int i = 0; i < ans; i++)
{
cout << nums[i] << " ";
}
return 0;
}
```