leetcode: explore-array-21 从排序数组中删除重复项

时间:2022-07-23
本文章向大家介绍leetcode: explore-array-21 从排序数组中删除重复项,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

leetcode explore 初级算法第一题:从排序数组中删除重复项。

题目分析

这里把题目贴出来:

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

一大片的英文字母…

我们来提练下题目的意思:

1、输入:是一个列表,同时是一个 sorted array nums,即排好序的列表,并且列表中只包含数字 2、输出:一个整数,这个整数是将列表中元素进行去重后的实际个数 3、in-place,这个单词经常在数组类的题目中出现,即原地修改数组,Do not allocate extra space for another array,两者意思是等价的 3、注意看 Clarification 这段话,它说明了题目的另一个要求,和 in-place 是一致的,即题目虽然输出是一个数字,但会去检查函数传入的那个列表,要求它的前 n 项必须依次是不重复的数字。

按照我们提练的题目意思,我们来看下题目中给的例子,计算步骤是什么样的:

nums = [0,0,1,1,1,2,2,3,3,4]

显然去重后,元素个数为 5

nums 需要依次进行去重,且只能在 nums 上进行修改
而最终 nums 的前 4 位必须是:

[0,1,2,3,4, ...],先后顺序也需要保持。

4后面之所以是省略号,是因为题目并不在乎后面的数字是什么。
It doesn't matter what values are set beyond the returned length.

同样,答案的检验也可以通过题目中给出来的代码来验证,代码是 Java 写的,但理解起来应该还是很容易的:

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

参考实现

题目看着很长,但其实很简单,实现的方法也很多,比如通过字典,如果要保证顺序也可以使用 OrderedDict,也可以简单的通过遍历来实现。参考代码如下:

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        i = 0
        j = 0
        while i < len(nums):
            f = nums[i]
            while i < len(nums) and nums[i] == f:
                i += 1
            nums[j] = f
            j += 1
        return j

说明

这个题目其实是简化过的,因为它的前提条件就是这个列表是 有序 的,这也提示我们,如果题目稍微换下,变成任意顺序的数组,我们要想到可以通过 排序 来简化题目。

点击阅读原文可查看题目