描述
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
思路:
本题是在一个已排好序的数组里去除重复元素,计算非重复元素的个数,解决方法是用一个变量index来记录非重复元素的个数,使用for循环来遍历数组,每当遇到一个新的数字时index增加1,需要注意的是,循环是从数组的第二个数开始,从第二个数开始与前一个数进行比较,最后返回的index需要加1(数组下标从零开始计算的)
代码1 python
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 1:
return 0
index = 0
for i in range(len(nums) - 1):
if nums[index] != nums[i + 1]:
index += 1
nums[index] = nums[i + 1]
return index + 1
代码2 c++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int index = 0;
for (int i = 1; i < nums.size(); i++){
if(nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
};
使用STL实现
代码3 c++
public:
int removeDuplicates(vector<int>& nums){
return distance(nums.begin(),unique(nums.begin(),nums.end()));
}