Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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], 变成[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.

自家:
\(O(n)\) time, \(O(1)\) space.

int removeDuplicates(vector<int> &nums) {
    if (nums.size() == 1) return 1;
    if (nums.size() == 0) return 0;
    int i = 1, k = 1;
    while (i < nums.size()) {
        if (nums[i] != nums[i - 1])
            nums[k++] = nums[i];
        i++;
    }
    return k;
}

人家:
\(O(n)\) time, \(O(1)\) space.

int removeDuplicates(vector<int> &A) {
    int count = 0;
    int n = A.size();
    for (int i = 1; i < n; i++) {
        if (A[i] == A[i - 1]) count++;
        else A[i - count] = A[i];
    }
    return n - count;
}
posted on 2017-08-13 13:38  英雄与侠义的化身  阅读(105)  评论(0编辑  收藏  举报