码迷,mamicode.com
首页 > 其他好文 > 详细

26_Remove Duplicates from Sorted Array

时间:2017-09-29 19:28:51      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:nts   turn   constant   重复   elements   ted   class   for   else   

/* 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. 
*/

解决思路:

  使用迭代器遍历vector,非重复时 length++,删除重复元素。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
    if (nums.size() == 0) return 0;
    int ans = 1;
    for (auto itr = nums.begin()+1; itr != nums.end();) {
        if (*itr == *(itr-1))   itr = nums.erase(itr);
        else {
            ans++;
            itr++;
        }
    }  
    return ans;
    }
};

discuss:

  题意不考虑vector中length之后的值,可以不做删除,选择覆盖前length 个元素 。稍快于解法1

int removeDuplicates(vector<int>& nums) {
    int i = !nums.empty();
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}

 

26_Remove Duplicates from Sorted Array

标签:nts   turn   constant   重复   elements   ted   class   for   else   

原文地址:http://www.cnblogs.com/zhangli-ncu/p/7612080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!