题目描述:
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3], Your function should return length = , with the first five elements ofnumsbeing1, 1, 2, 2and 3 respectively. It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length =7, with the first seven elements ofnumsbeing modified to , 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length.
必须直接修改数组,每个值最多出现两次,只能使用常数空间。由于是有序数组,可以使用两个指针,i在前指向下一个插入的位置,j在后表示当前遍历的位置,当nums[j]!=nums[i-2],就可以把nums[j]插入至nums[i],最后的数组长度就是i。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<=2) return nums.size();
int i=2;
int j=2;
while(j<nums.size())
{
if(nums[j]!=nums[i-2])
{
nums[i]=nums[j];
i++;
}
j++;
}
return i;
}
};
287

被折叠的 条评论
为什么被折叠?



