26. Remove Duplicates from Sorted Array

来源:互联网 发布:软件开发立项申请表 编辑:程序博客网 时间:2024/06/05 12:49

题目:Remove Duplicates from Sorted Array

原题链接:https://leetcode.com/problems/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.

给出一个排序好的数组,删除数组中的重复元素,并且返回最新的值。
不允许新建额外的数组,使用常数级的内存。

例,给出数组[1,1,2]
返回长度为2,数组中元素为[1,2]

设now和cnt,now表示当前扫描的元素的下标,cnt表示下标为0到cnt - 1部分是对应下标0到now - 1部分已经整理好的结果。
让now和cnt同时向后扫描,如果nums[now] != nums[cnt - 1],说明当前元素与前面的是不重合的,将其覆盖到前面去,即nums[cnt++] = nums[now++],如果nums[now] == nums[cnt - 1],说明这是一个重复的元素,让now继续往下扫描即可。

代码如下:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int len = nums.size();        if(len <= 1) return len;        int now = 0, cnt = 0;        while(now < len) {            if(now == 0) {                cnt++;                now++;            }else{                if(nums[now] == nums[cnt - 1]) {                    while(now < len && nums[now] == nums[cnt - 1]) {                        now++;                    }                    if(now < len) {                        nums[cnt] = nums[now];                        cnt++;                        now++;                    }                }else{                    nums[cnt] = nums[now];                    now++;                    cnt++;                }            }        }        nums.erase(nums.begin() + cnt, nums.end());        return cnt;    }};
0 0
原创粉丝点击