当前位置: 首页 > news >正文

3.11记录

leetcode刷题:

1. 334. 递增的三元子序列 - 力扣(LeetCode)

方法一:使用贪心算法求解
class Solution(object):
    def increasingTriplet(self, nums):
        first = nums[0]
        second = float('inf')
        for i in nums:
            if i>second:
                return True
            elif i>first:
                second=i
            elif i<first:
                first=i
        return False

这种方法通过不断地贪心来解决问题。首先解决的是最大值,如果达到a<b<c那么就直接true,其次是次大,如果比最大值小比最小值大,那么就是次大,最后如果比最小值还小,说明成就递增三元子序列的可能更大一点。

#方法二:用数组来维护
class Solution(object):
    def increasingTriplet(self, nums):
        n=len(nums)
        left,right=[float("inf")]*n,[float("-inf")]*n
        # 维护两个数组,left表示不包括此时左侧的最小值,right表示不包括此时的右侧的最大值
        for i in range(1,n):
            left[i]=min(left[i-1],nums[i-1])
        for i in range(n-2,0,-1):
            right[i]=max(right[i+1],nums[i+1])
        for i in range(1, n - 1):
            if left[i] < nums[i] < right[i]:
                return True
        return False
        

这种方法维护了两个数组,分别是left和right,其中left表示当前数字左边的比当前数字小的,right表示当前数字右边的比当前数字大的,然后再比较left<nums<right,如果满足这个条件,说明存在递增子序列,如果不满足,则证明不存在,返回False

2.1657. 确定两个字符串是否接近 - 力扣(LeetCode)

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        dict1=Counter(word1)
        dict2=Counter(word2)
        return dict1.keys()==dict2.keys() and sorted(dict1.values())==sorted(dict2.values())

首先比较字符出现是否一样,然后比较字符出现的次数是否一样。

plus:当不能替换的时候,就直接

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        dict1=Counter(word1)
        dict2=Counter(word2)
        return dict1==dict2

3.437. 路径总和 III - 力扣(LeetCode)

class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
        if root is None:
            return 0
        def dfs(root,target):
            count=0
            if root.val==target:
                count+=1
            if root.left:
                count+=dfs(root.left,target-root.val)
            if root.right:
                count+=dfs(root.right,target-root.val)
            return count
        return dfs(root,targetSum)+self.pathSum(root.left,targetSum)+self.pathSum(root.right,targetSum)

这道题难点在于是否考虑本节点被选择,以及dfs的运用。

相关文章:

  • 美团AI面试面经
  • Microsoft Dragon Copilot:医疗AI革命开启,用语音终结手写病历时代
  • jQuery干货
  • 网络接口松动为什么会导致高延迟
  • Linux:多线程(单例模式,其他常见的锁,读者写者问题)
  • openai-agents 安装与测试
  • 信息学奥赛c++语言:整数去重
  • 3-001:MySQL 中的回表是什么?
  • 中国软件供应链安全技术指南|DevSecOps敏捷安全技术金字塔V3.0正式发布
  • MQ消息发送不在MySQL事务中,该如何保证一致性?
  • 蓝桥 2109统计子矩阵
  • Ubuntu22.04安装数据
  • 5.1 程序调试
  • 什么是双机热备系统?双机热备现在是否已经过时了?
  • 职坐标C语言数据结构算法核心精讲
  • Deep research深度研究:ChatGPT/ Gemini/ Perplexity/ Grok哪家最强?(实测对比分析)
  • 内容中台的实施基石是什么?
  • vue2双向绑定解析
  • 单片机设计暖脚器研究
  • 投资晚报 3.12
  • 五一假期首日,省级党政“一把手”夜访商业街区
  • 美法官裁定特朗普援引战时法律驱逐黑帮违法,系首次永久性驳回
  • 对谈|“对工作说不”是不接地气吗?
  • 缔造“水饺皇后”的香港,也是被移民塑造的香港
  • 人民日报评论员:因势利导对经济布局进行调整优化
  • 印度宣布即日起对所有巴基斯坦航班关闭领空