leetcode 26

26. 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位。

代码如下:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.empty())
        {
            return 0;
        }
        int n = nums.size();
        if(n == 1)
        {
            return 1;
        }
        int sum = 1;
        int j = 0;
        for(int i = 1; i < n; i++)
        {
            if(nums[j] != nums[i])
            {
               nums[j+1] = nums[i];
               sum++;
               j++;
            }
            
        }
        return sum;
    }
};
原文地址:https://www.cnblogs.com/shellfishsplace/p/5848472.html