您的位置:首页 > 运维架构

Leetcode 26. Remove Duplicates from Sorted Array

2017-01-26 10:07 459 查看
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.

思路:

1. 把重复的数交换到后面去。维持一个长度逐渐增加的起始位置变化的多余的elements,例如:

1,1,1,2,2,3,4,4


当遍历到第二个1,发现等于当前最大值(=1),则需要用left指针指向这个位置,然后用right指针从这里继续遍历;当right指针遇到2,则更新最大值等于2,且让right指向的数和left指向的数交换,left往后移动一下,right继续移动;当right指向的值还=2,等于最大值,不需要移动left;

2. two pointer:这里是两个指针都从左边移动,昨天遇到的情况是一个左边,一个右边,都往中间移动!形式不同,但都是two pointer

//two pointer
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
//
int left=0,right=0;
int mx=INT_MIN;
for(int right=0;right<nums.size();right++){
if(nums[right]>mx){
mx=nums[right];
swap(nums[left],nums[right]);
left++;
}
}
return left;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode twopointer