(leetcode题解)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.

这道题要求删除给定排列好的数组中重复的数子,记录剩余的数组大小。

运用两个指示下标,直接比较相邻两个数,相同就剔除第二个,不同则保留。

C++实现如下:

int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
            return 0;
        int res=1;
        for(int i=1,j=0;i<nums.size();)
        {
            if(nums[j]!=nums[i])
            {
                nums[++j]=nums[i];
            }
            else 
                i++;
            res=j+1;
        }
        return res;
    }

 

posted on 2017-06-09 15:41  kiplove  阅读(114)  评论(0编辑  收藏  举报

导航