题目:
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.
For example,
Given input array 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.
答案一(利用容器):
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int ns = nums.size();
if (ns == 0) {
return 0;
}
int i = 0;
while (i < ns - 1) {
if (nums[i] == nums[i + 1]) {
nums.erase(nums.begin() + i + 1);
ns--;
} else {
i++;
}
}
return ns;
}
};
答案二(Java):
双指针。直接改变数组,当出现重复的数的时候,跳过;当数不重复时,赋值给较慢的指针,最终的结果是数组前面一部分没有重复的值,后面的数字无意义,由于会返回数组的大小。因此还是可以区分。
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
}