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.

http://www.lintcode.com/en/problem/remove-duplicates-from-sorted-array/

Solution


简单。

int removeDuplicates(vector<int> &nums) {
        // write your code here
        int n = nums.size();
        if (n==0) return 0;
        int bro = nums[0];
        int result = 1;
        for(int i=1; i<n; i++) {
            if(nums[i] == bro)
                continue;
            bro = nums[i];
            nums[result] = bro;
            result++;
        }
        return result;
    }

代码优化

int removeDuplicates(vector<int> &nums) {
        // write your code here
        int n = nums.size();
        if (n==0) return 0;
        int result = 0;
        for(int i=1; i<n; i++) {
            if(nums[i] != nums[result])
                nums[++result] = nums[i];
        }
        return result;
    }

results matching ""

    No results matching ""