[LeetCode]Remove Duplicates from Sorted Array题解

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.

这道题的意思是,给定一个排好序的数组,返回这个数组排除重复数字之后的长度n,并且这个数组的前n个数字是合并重复数字后的数字。例如,{1,1,2}不仅要返回长度2,还要使这个数组的前两位变成1,2。
题目要求不能另开一个数组。

最终的解决方案时间复杂度为O(n):

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int n : nums)
            if (!i || n > nums[i-1])
                nums[i++] = n;
        return i;
    }
};
posted @ 2017-09-24 23:13  liangf27  阅读(85)  评论(0编辑  收藏  举报