【LeetCode】Remove Duplicates from Sorted Array

版权声明: https://blog.csdn.net/ysq96/article/details/89918478

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 1:

Given 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 returned length.

Example 2:

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.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// 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]);
}

题意:题目给定一个有序的数组,要求删除掉重复的多余数字,然后再修改成有序的数组,输出这个数组中的个数

C++:这个方法还需要优化

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        set<int> book;
        for(int i=0;i<nums.size();i++)book.insert(nums[i]);
        int index=0;
        for(auto it=book.begin();it!=book.end();it++,index++){
            nums[index]=*it;
        }
        return book.size();
    }
};

优化

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

Python3:

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        nums_len=len(nums)
        if nums_len<=1:
            return nums_len
        i=0
        for j in range(nums_len):
            if nums[i]!=nums[j]:
                i+=1
                nums[i]=nums[j]
        return i+1

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/89918478