Leetcode:26. Remove Duplicates from Sorted Array

问题描述:
Given a sorted array nums, 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 = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

这里有个解释:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

这里题目的意思是给定一个数组,里面的元素有可能是重复的,那么计算出总共有多少个不同的元素,并且原数组的前n个数就是对应不同的元素。

这个难度等级是简单

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

            }
        }
        return count;

    }
};

(⊙o⊙)嗯!↖(^ω^)↗

猜你喜欢

转载自blog.csdn.net/Felaim/article/details/80379955
今日推荐