LeetCode 26.Remove Duplicates from Sorted Array
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.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn’t matter what you leave beyond the new length.
解析:
输入一组有序数组,去掉重复元素,并将元素数目返回。不能用额外的数组。
解法1:
采用两个指针,快慢指针来记录遍历的坐标,最开始时两个指针都指向第一个数字,如果两个指针指的数字相同,则快指针向前走一步,如果不同,则两个指针都向前走一步,这样当快指针走完整个数组后,慢指针当前的坐标加1就是数组中不同数字的个数。
代码如下:
[cc lang=”C++”]
class Solution {
public:
int removeDuplicates(vector
if(nums.empty()) return 0;
int index = 0;
for(int i=1; i < nums.size(); i++)
{
if(nums[index] != nums[i])
{
nums[++index] = nums[i];
}
}
return index + 1;
}
};
[/cc]
方法2:
还有一种更讨巧的方法,借用已经C++已经提高的函数。
[cc lang="C++"]
class Solution {
public:
int removeDuplicates(vector
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};
[/cc]