Remove Duplicates from Sorted Array
Analysis
周末下午日常刷题啦~ 下周末或者下下周一表妹就要来上海玩啦,所以下周末可能就没时间刷题了,但是寒假会有很多时间刷题哦~
Given a sorted array, 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.
这道题还是很简单啦,就是说给我一个数组,然后对这个数组进行去重,最后统计出去重之后的数组中的元素个数。这里需要注意的是,这个给我们的数组里面的元素已经按着从小到大的顺序排好了,然后题目的要求是空间复杂度为O(1),也就是说我们不能再开一个数组用来记录,因此我们直接用两个指针对数组进行扫描就行了。一个指针是pre,另一个是cur。pre表示前面一个元素,cur表示现在扫描到的元素。所以当pre所指的元素等于cur所指的元素,那么就说明出现重复元素,则让cur+1然后接着扫描下一个,否则说明相邻元素不是重复的,那就让pre+1,同时让cur+1,然后继续扫描。
implement
@Cherry Ye
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
return 0;
int pre = 0;
int cur = 0;
int n = nums.size();
while(cur<n){
if(nums[pre]==nums[cur])
cur++;
else{
nums[++pre] = nums[cur];
cur++;
}
}
return pre+1;
}
};