【力扣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写起来还是很顺手滴
相关推荐
_Kayo_5 小时前
node.js 学习笔记3 HTTP
笔记·学习
PAK向日葵5 小时前
【算法导论】PDD 0817笔试题题解
算法·面试
地平线开发者8 小时前
ReID/OSNet 算法模型量化转换实践
算法·自动驾驶
地平线开发者8 小时前
开发者说|EmbodiedGen:为具身智能打造可交互3D世界生成引擎
算法·自动驾驶
星星火柴9369 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑10 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
闪电麦坤9511 小时前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
C++、Java和Python的菜鸟11 小时前
第六章 统计初步
算法·机器学习·概率论
Cx330❀11 小时前
【数据结构初阶】--排序(五):计数排序,排序算法复杂度对比和稳定性分析
c语言·数据结构·经验分享·笔记·算法·排序算法