LeetCode/026-Remove Duplicates from Sorted Array/README.md
2018-09-01 18:42:01 +08:00

20 lines
671 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 思路
由于是已经排序好的数组,所以相同的数肯定是相邻的,遍历数组时跳过与上一个数重复的数即可。
可以用一个count记录在下标count及之前是没有重复的数组 count初始化为0然后从前往后遍历若a[i]==a[count]说明重复不更新count
否则应该让count++。注意单独判断空数组。
# C++
```
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty()) return 0;
int count = 0;
for(int i = 1; i < nums.size(); i++){
if(nums[i] != nums[count]) nums[++count] = nums[i];
}
return count+1;
}
};
```