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 in place with constant memory.
Example
Given input array A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
解题思路:
双指针法。使用两个指针分别标记一前一后元素,一起遍历,若两个指针所指元素的值相等,则删除后一指针的值,这样就能保证在有序的数组中,没有不相同的元素。
class Solution { public: /* * @param nums: An ineger array * @return: An integer */ int removeDuplicates(vector<int> &nums) { // write your code here if(nums.size()< 2) return nums.size(); vector<int>::iterator cur = nums.begin(); vector<int>::iterator afr = nums.begin()+1; while(afr != nums.end()) { if(*cur == *afr) nums.erase(afr); else { cur++; afr++; } } return nums.size(); } };