【leetcode】 26. Remove Duplicates from Sorted Array

@requires_authorization
@author johnsondu
@create_time 2015.7.22 18:58
@url [remove dublicates from sorted array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
/**
 * @description: 从有序数组中剔除元素,最多常量额外空间,设置标兵依次比較
 * @time_complexity: O(n)
 * @space_complexity: O(1)
 */
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        const int len = nums.size();
        if(len < 2) return len;
        int first = nums[0];
        int idx = 1;
        for(int i = 1; i < len; i ++) {
            if(nums[i] == first) continue;
            else {
                first = nums[i];
                nums[idx] = first;
                idx ++;
            }
        }
        return idx;
    }
};

posted on 2017-08-12 16:23  yjbjingcha  阅读(257)  评论(0编辑  收藏  举报

导航