【力扣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写起来还是很顺手滴
相关推荐
然我15 分钟前
链表指针玩不转?从基础到双指针,JS 实战带你破局
前端·数据结构·算法
巴伦是只猫19 分钟前
【深度学习笔记】2 浅层神经网络
笔记·深度学习·神经网络
EndingCoder23 分钟前
算法与前端的可访问性
前端·算法·递归·树形结构
wb18926 分钟前
LVS的集群技术和分布式
运维·笔记·分布式·云计算·lvs
ysa0510301 小时前
竞赛常用加速技巧#模板
c++·笔记·算法
7 971 小时前
C语言基础知识--文件的顺序读写与随机读写
java·数据结构·算法
2401_841003981 小时前
Kubernetes 资源管理全解析
算法·贪心算法
☆璇2 小时前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
特种加菲猫2 小时前
硬件与软件的桥梁:冯诺依曼体系、操作系统和初始进程的深度解析
linux·笔记
云和数据.ChenGuang3 小时前
gitlab-ci.yml
面试·职场和发展·gitee·运维面试题·运维技术总结