题目描述:
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]
.
这题还是用two pointers,一个i去遍历,一个idx守在原地。如果A[i] == A[idx],就不取A[i];否则,A[idx + 1] = A[i]。
Mycode(AC = 42ms):
class Solution {
public:
/**
* @param A: a list of integers
* @return : return an integer
*/
int removeDuplicates(vector<int> &nums) {
// write your code here
if (nums.size() <= 1) return nums.size();
int idx = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[idx]) {
nums[idx + 1] = nums[i];
idx++;
}
}
return idx + 1;
}
};