[用 Python 解 LeetCode] (001) 27. Remove Element

题干懒人包

输入一个数组及一个数,最後输出一个数值代表非重复数值的数量,然後以下几点要注意:

  1. 只能修改该数组,利用的空间复杂度最多为1(意思就是不能创建新的数组append值)

  2. 不用管超过回传值以後nums的值

    """
    比方说输入的 nums = [0,1,2,2,3,0,4,2], val = 2
    那最後回传值要等於五,且 nums[:5] 要包含 0, 1, 2, 3, 4 这几个数字,然後数字在该切片里的顺序不重要
    """
    

解法

遍历数组,把跟 val 一样的元素进行交换,用 i 移动然後 tail 标记非重复跟重复交界

class Solution:
    def removeElement(self, nums, val: int) -> int:
        i = 0
        tail = len(nums) - 1
        while i <= tail:
            if nums[i] != val:
                i += 1
            else:
                nums[i], nums[tail] = nums[tail], nums[i]
                tail -= 1
        return i

solution = Solution()
print(solution.removeElement([2, 2, 3, 3], 3))


别人的解法

因为此题干不需要知道nums後面接着是甚麽,所以这里不用交换(上面其实也可以不用)。

class Solution(object):
    def removeElement(self, nums, val):
        j = 0
        for i in nums:
            if i != val:
                nums[j] = i
                j += 1
        return j

这里有提到

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
# It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.

<<:  PI型的CISSP

>>:  AlwaysOn 可用性群组 (AOAG) - 心得分享

Day 24. slate × Normalizing

在开始继续深入源码之前,我们先花点篇幅讨论 Normalizing 这回事。 Normalizin...

[DAY 03] EC2

EC2 (Elastic Compute Cloud) 这是 AWS 服务中最为经典以及最受欢迎的项...

[Day 03] if条件、缩排规则、函式写法,以及一些字串技巧

[ 30 Days of ML Challenge | D03] 今天提供一个文件以及一个练习教材,...

# Day 26 Page migration (一)

文件 原文文件:Page migration 翻译: .. _page_migration: ===...

强型闯入DenoLand[29] - 去标签密技

强型闯入DenoLand[29] - 去标签密技 笔者在昨天非常粗略地介绍了 Oak 的概念。此外...