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.

思路:

很巧妙的使用一个len的变量,使得我每次都在最外面如果i值与len不相等,都加1,

如果相等不进行任何操作,这时候len不变化使得最终长度保持不变。

代码:

 

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
            return 0;
        int size=nums.size();
        int len=0;
        
        for(int i=1;i<size;i++){
            if(nums[i]!=nums[len]){
                nums[++len]=nums[i];
            }
        }
        return len+1;
    }
};


 

posted @ 2015-12-06 22:23  JSRGFJZ6  阅读(107)  评论(0编辑  收藏  举报