您的位置:首页 > 其它

LeetCode : Remove Duplicates from Sorted Array

2016-09-27 19:00 246 查看
常规方法是使用双指针。

int removeDuplicates(vector<int>& nums)
{
if(nums.size() < 2)
return nums.size();

int left = 1;
while(left < nums.size())
{
if(nums[left] == nums[left - 1])
break;
left ++;
}

int right = left + 1;
while(right < nums.size())
{
if(nums[right] == nums[right - 1])
right ++;
else
{
nums[left] = nums[right];
left ++;
right ++;
}
}

return left;
}


只使用容器看起来比较简洁,但是效率会降低。

int removeDuplicates(vector<int>& nums)
{
set<int> s(nums.begin(), nums.end());
nums.assign(s.begin(), s.end());
return s.size();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode