【二】Leetcode之Python刷题之路

这篇博客主要介绍了在LeetCode上使用Python解决三个算法问题:1. 移动零,要求原地修改数组;2. 多数元素,寻找出现次数超过n/2的元素;3. 最佳买卖股票时机,找到最大利润。对于每个问题,博主分别给出了自己的解题思路和优化方案,并讨论了其他高效的解法。

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

1. Move Zeros

给一个数组,将数组里的0全部移到数组最后。
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

LeetCode里很多题目要求”do this in-place”,通俗的理解就是算法输出结果覆盖算法的输入,这样做可以节省内存。
我的代码实现如下:

class Solution(object):
    def moveZeroes(self, nums):
        for i in range(nums.count(0)):
            nums.remove(0)
        nums.extend([0]*count0)

思路比较简单,由于remove(x)函数每次只能删除第一个遇到的x,因此这里首先将所有0移除,然后在最后用extend()的方法将0添加到nums最后。

2. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

  我最开始的思路是遍历nums中所有的元素,然后count每个元素出现的次数,提交代码的时候被拒绝了,结论是:”Runtime Limited Error”超时了。确实,这样的实现方法时间复杂度为 O(

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值