题目描述:
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.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i=0;
int j=0;
while(j<nums.size())
{
if((j>0&&nums[j]!=nums[j-1])||j==0)
{
nums[i]=nums[j];
i++;
}
j++;
}
return i;
}
};

本文介绍了一种在不使用额外空间的情况下从已排序数组中去除重复元素的方法。通过双指针技巧,仅保留唯一值并返回新长度。示例代码展示了如何实现这一功能。
344

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



