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 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.
题解:
给定一个排序的数组,删除重复,使每个元素只显示一次并返回新的长度。
不开另外的数组,使得原数组前几位(new length)即为去重后结果。
solution1:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty() == true) {
return 0;
}
int j = 0;
/* 取数组首位元素为参考点 j=0
向后查找,遇到第一个与此元素不同的数,
则参考点更新 j++, 并把此值赋给nums[j] */
for (int i = 1; i < nums.size(); i++) {
if (nums[j] != nums[i]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
};
solution2:
/* 直接使用STL*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};