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

leetcode代码 50道答案

简单难度:两数之和

def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []

简单难度:有效的括号

def isValid(s):
    stack = []
    mapping = {")": "(", "}": "{", "]": "["}
    for char in s:
        if char in mapping:
            top_element = stack.pop() if stack else '#'
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)
    return not stack

中等难度:三数之和

def threeSum(nums):
    nums.sort()
    res = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        l, r = i + 1, len(nums) - 1
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            if s < 0:
                l += 1
            elif s > 0:
                r -= 1
            else:
                res.append([nums[i], nums[l], nums[r]])
                while l < r and nums[l] == nums[l + 1]:
                    l += 1
                while l < r and nums[r] == nums[r - 1]:
                    r -= 1
                l += 1
                r -= 1
    return res

 

中等难度:盛最多水的容器

def maxArea(height):
    max_area = 0
    l, r = 0, len(height) - 1
    while l < r:
        max_area = max(max_area, min(height[l], height[r]) * (r - l))
        if height[l] < height[r]:
            l += 1
        else:
            r -= 1
    return max_area

 

http://www.lryc.cn/news/491155.html

相关文章:

  • Centos-stream 9,10 add repo
  • 【隐私计算大模型】联邦深度学习之拆分学习Split learning原理及安全风险、应对措施以及在大模型联合训练中的应用案例
  • DataWhale—PumpkinBook(TASK05决策树)
  • elasticsearch7.10.2集群部署带认证
  • Java基础-I/O流
  • 全面解析多种mfc140u.dll丢失的解决方法,五种方法详细解决
  • 详细探索xinput1_3.dll:功能、问题与xinput1_3.dll丢失的解决方案
  • InfluxDB时序数据库笔记(一)
  • Spring Boot 3.x + OAuth 2.0:构建认证授权服务与资源服务器
  • 2024年09月CCF-GESP编程能力等级认证Scratch图形化编程二级真题解析
  • Linux 正则表达式(basic and extened)
  • GB 35114-2017 学习笔记(规避版权阉割版)
  • YOLO-FaceV2: A Scale and Occlusion Aware Face Detector
  • 进程间通信--详解
  • 零基础上手WebGIS+智慧校园实例(1)【html by js】
  • 【Github】如何使用Git将本地项目上传到Github
  • 集合Queue、Deque、LinkedList、ArrayDeque、PriorityQueue详解
  • 谈一下开源生态对 AI人工智能大模型的促进作用
  • 基于python的机器学习(四)—— 聚类(一)
  • 实时数据开发 | 怎么通俗理解Flink容错机制,提到的checkpoint、barrier、Savepoint、sink都是什么
  • C++设计模式-策略模式-StrategyMethod
  • 小程序免备案:快速部署与优化的全攻略
  • Jmeter中的定时器
  • C++自动化测试:GTest 与 GitLab CI/CD 的完美融合
  • vscode连接远程开发机报错
  • 神经网络12-Time-Series Transformer (TST)模型
  • IDEA 2024安装指南(含安装包以及使用说明 cannot collect jvm options 问题 四)
  • Fakelocation Server服务器/专业版 Centos7
  • oracle的静态注册和动态注册
  • 机器翻译基础与模型 之四:模型训练