leetcode-26-remove duplicates from sorted array

Problem 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 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.

题目大意:

给定一个已排序的数组,去除重复元素, 然后返回新的长度,只能使用O(1)的额外空间。

Solutions:

很简单的一次遍历即可。当某个数比它前一个数大的时候说明它是新的一个未重复元素。

Code in C++:

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