一
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.
总结:
相似题:
移出元素 Remove Element
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if(len<=1){
return len;
}
int i = 0;
for (int j = 1; j < len; j++){
if (nums[j] != nums[j - 1]){
nums[++i] = nums[j];
}
}
return i + 1;
}
};
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if(len<=1){
return len;
}
int i = 0;
for (int j = 1; j < len; j++){
if (nums[j] != nums[j - 1]){
nums[++i] = nums[j];
}
}
return i + 1;
}
};
二
Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3]
,
Your function should return length = 5
, with the first five elements of nums being 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.
跟已经去重好的比较。
1.当nums的size小于等于2时,直接返回
2.i,j从索引2开始;。。。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=2) return nums.size();
int i = 2;
for (int j = 2; j < nums.size(); j++){
if ((nums[j] != nums[i-1]) || ( nums[j] == nums[i-1] && nums[j] != nums[i - 2])){
swap(nums[i++], nums[j]);
}
}
return i;
}
};