关关的刷题日记07——Leetcode 26. Remove Duplicates from Sorted Array 方法1

时间:2022-05-07
本文章向大家介绍关关的刷题日记07——Leetcode 26. Remove Duplicates from Sorted Array 方法1,主要内容包括关小刷刷题07 – Leetcode 26. Remove Duplicates from Sorted Array 方法1、方法1、方法2、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关小刷刷题07 – Leetcode 26. Remove Duplicates from Sorted Array 方法1

题目

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.

题目的意思是:排好序的数组中会有一些重复的数,要在不额外开辟空间的情况下删掉重复的数,返回不重复的数的长度。至于新长度之外还有哪些数就不用管了。

方法1

方法1:在关小刷刷题05 – Leetcode 217. Contains Duplicate中,有没有发现unique是个好东西?又能去重,又能直接返回新长度啊。Unique时间复杂度O(n)。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        return unique(nums.begin(), nums.end())-nums.begin();
    }
};

方法2

方法2:如果面试的时候不让用unique怎么办呢,那就把不重复的数一点点往前搬了,我是一个小小搬运工,我搬呀搬呀搬。顺便把搬了多少数记录下来,返回。且听下回分解。

人生没有白走的路,每一步都算数,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。