描述
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
思路:
这道题是上一篇的升级版,允许最多有两个重复的数字,与上一篇思路基本一致,额外一个变量来记录次数,注意index的初值以及判断数值不等时的改变,如果是未排序的数组则需要引入一个hashmap来记录出现的次数。
代码1 python
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 3:
return len(nums)
index = 2
for i in range(len(nums) - 2):
if nums[index - 2] != nums[i+2]:
nums[index] = nums[i+2]
index += 1
return index
代码2 c++
class Solution:
public:
int removeDuplicates(vector <int>& nums){
if (nums.size() <= 2) return nums.size();
int index = 2;
for (int i = 2 ; i < nums.size(); i++){
if(nums[index - 2] != nums[i])
nums[index++] = nums[i];
}
return index;
}
下面再提供一种思路,自行理解
代码3 c++
class Solution:
public:
int removeDuplicates(vector <int>& nums){
int n = nums.size();
int index = 0;
for (int i = 0 ; i < n; ++i){
if( i >0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i +1])
continue;
nums[index++] = nums[i];
}
return index;
}
网友评论