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.
Hide Tags
两个下标,遇到重复的jj向前,直到遇到新值才复制新值。
注意jj向前的时候需要保护。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int ii = 0;
if(nums.size())
{
for(int jj=0; jj<nums.size(); )
{
nums[ii++] = nums[jj++];
while((nums[ii-1] == nums[jj])&&(jj<nums.size()))
jj++;
}
}
return ii;
}
};
32 ms.
No comments:
Post a Comment