【力扣hot100】刷题笔记Day3

前言

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

283. 移动零 - 力扣(LeetCode)

  • 一个指针遍历,一个指针用于交换前面的0
  • 【力扣hot100】刷题笔记Day3_第1张图片
  • 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)

  • 左右双指针,柱子较矮的往中间靠拢(因为最大盛水容器受限于最矮柱子)
  • 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++版本的思路,排序 + 双指针 +剪枝去重
  • 【力扣hot100】刷题笔记Day3_第2张图片
  • 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)

  • 灵神的题解很清晰,除了之前刷的单调栈的思路,这里用相向双指针前后更新最高柱子
  • 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写起来还是很顺手滴 

你可能感兴趣的:(力扣hot100刷题笔记,leetcode,笔记,算法,职场和发展,数据结构)