美文网首页
26. Remove Duplicates from Sorte

26. Remove Duplicates from Sorte

作者: weego | 来源:发表于2018-04-07 10:25 被阅读0次

    Description

    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 by modifying the input array [in-place] with O(1) extra memory.

    Example:
    Given 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.
    

    Solution

    删除有序数组中的重复元素,返回不重复元素的个数k,保证数组前k个位置元素ok就行,后n-k个位置存什么不管

    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        int index = 0;//存放当前未重复数据的最右端位置
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[index] != nums[i]) {//借助数组有序,可以直接遍历去比较
                nums[++index] = nums[i];//如果找到不重复,放到下一个坑里
            }
        }
        return index + 1;
    }
    

    相关文章

      网友评论

          本文标题:26. Remove Duplicates from Sorte

          本文链接:https://www.haomeiwen.com/subject/fngehftx.html