【力扣hot100】刷题笔记Day3

前言

  • 以撒真是一不小心就玩太久了,终于解锁骨哥嘞,抓紧来刷题,今天是easy双指针!

283. 移动零 - 力扣(LeetCode)

  • 一个指针遍历,一个指针用于交换前面的0
python 复制代码
class Solution(object):
    def moveZeroes(self, nums):
        pre = 0  # 用于交换前面的0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[pre] = nums[pre], nums[i]  # 交换
                pre += 1
        return nums

11. 盛最多水的容器 - 力扣(LeetCode)

  • 左右双指针,柱子较矮的往中间靠拢(因为最大盛水容器受限于最矮柱子)
python 复制代码
class Solution(object):
    def maxArea(self, height):
        l, r = 0, len(height) - 1  # 首尾双指针
        res = 0
        while l != r:  # 往中间靠拢
            # 记录最大雨水量
            res = max(res, min(height[l], height[r]) * (r - l))  
            if height[l] < height[r]:  # 较矮的往中间移,相等随便
                l += 1
            else:
                r -= 1
        return res

15. 三数之和 - 力扣(LeetCode)

  • 基本沿袭之前三数之和C++版本的思路,排序 + 双指针 +剪枝去重
python 复制代码
class Solution(object):
    def threeSum(self, nums):
        res = list()
        nums.sort()  # 先排序
        n = len(nums)
        for i in range(n):
            if nums[i] > 0:  # 大于0后面不可能相加等于0了,直接break
                break
            if i > 0 and nums[i] == nums[i - 1]:  # i去重
                continue
            l, r = i + 1, n - 1  # 前后双指针
            while l < r:
                sum = nums[i] + nums[l] + nums[r]
                if sum < 0:
                    l += 1
                elif sum > 0:
                    r -= 1
                else:
                    res.append([nums[i], nums[l], nums[r]])
                    while l < r and nums[l + 1] == nums[l]:  # l去重
                        l += 1
                    while l < r and nums[r - 1] == nums[r]:  # r去重
                        r -= 1
                    l += 1
                    r -= 1
        return res

42. 接雨水 - 力扣(LeetCode)

  • 灵神的题解很清晰,除了之前刷的单调栈的思路,这里用相向双指针前后更新最高柱子
python 复制代码
class Solution:
    def trap(self, height: List[int]) -> int:
        res = l_max = r_max = 0
        l, r = 0, len(height) - 1  # 相向双指针
        while l < r:
            l_max = max(l_max, height[l])  # 左边最高
            r_max = max(r_max, height[r])  # 右边最高
            if l_max < r_max:  # 单格雨水受限于两侧较小的最高柱
                res += l_max - height[l]
                l += 1
            else:
                res += r_max - height[r]
                r -= 1
        return res

后言

  • 有前面的基础,刷起题目一下子就能懂啦,而且python写起来还是很顺手滴
相关推荐
海梨花几秒前
字节面试高频算法题
java·算法·面试·职场和发展
aqiu1111117 分钟前
python02
算法
瓦特what?7 分钟前
位运算核心技巧与应用
java·jvm·算法
无限码力7 分钟前
阿里算法岗 0530笔试真题 - 荆棘林的最优砍断计划
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试真题·阿里巴巴笔试真题
人道领域9 分钟前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode
随意起个昵称10 分钟前
线性dp-LIS题目5(导弹拦截,二分优化)
c++·算法·动态规划
winlife_11 分钟前
全程用 AI 做一款商业级手游 · EP10 道具系统:让三个按钮真正改变棋盘
windows·算法·unity·ai编程·游戏开发·mcp·玩法系统
IT策士11 分钟前
Redis 从入门到精通:数据结构Set 与 Sorted
数据结构·数据库·redis
计算机安禾14 分钟前
【数据库系统原理】第16篇:范式理论(下):多值依赖与第四范式——消除非平凡的非函数依赖
算法
lqqjuly19 分钟前
一致性模型深度解析
人工智能·深度学习·算法