高级编程技术 Python 第九周作业

本文解析了LeetCode上的两个经典题目:MoveZeroes(#283)和SearchInsertPosition(#35)。针对MoveZeroes问题,介绍了如何通过遍历数组、记录0的数量并在数组末尾追加0的方法解决问题;对于SearchInsertPosition问题,则使用了二分查找法来高效解决。文章还提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Move Zeroes (#283)

来源:https://leetcode.com/problems/move-zeroes/description/

题意:

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

分析:

访问一遍数组,记录0的个数tot,并在数组末尾append上tot个0,最后remove去tot个0。利用list的remove函数功能,每次删去的都是数组中的第一个0,不会把末尾的0删去。

def moveZeroes(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    n = len(nums)
    tot = 0
    for i in range(0, n):
        if nums[i] == 0:
            nums.append(0)
            tot = tot+1
    for i in range(0, tot):
        nums.remove(0)

状态:


这种方式看起来比较慢,排在leetcode榜的很后面。

Search Insert Position (#35)

来源:https://leetcode.com/problems/search-insert-position/description/

题意:

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

分析:简单的二分查找。

def searchInsert(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    l = 0
    r = len(nums)-1
    while l <= r:
        mid = int((l+r)/2)
        if nums[mid] < target:
            l = mid+1
        else:
            r = mid-1
    return l
    

状态:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值