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

2024.3.31力扣(1200-1400)刷题记录

一、1523. 在区间范围内统计奇数数目

1.模拟

class Solution:def countOdds(self, low: int, high: int) -> int:# 模拟return len(range(low,high+1,2)) if low & 1 else len(range(low+1,high+1,2))

2.数学

总结规律。首为偶数就向下取整;奇数就向上取整。注意整数向上向下取整值相同。

class Solution:def countOdds(self, low: int, high: int) -> int:# 数学return (high - low + 1) // 2 if low % 2 == 0 else ceil((high - low + 1) / 2)

3.前缀和。来自官方题解(. - 力扣(LeetCode))。

class Solution:def countOdds(self, low: int, high: int) -> int:# 前缀和# 前low-1包含的奇数 - 前high包含的奇数,从0开始def pre_odd(num):return (num + 1) // 2return pre_odd(high) - pre_odd(low - 1)

 二、1822. 数组元素积的符号

遍历

class Solution:def arraySign(self, nums: List[int]) -> int:# 遍历# 有0为0,无0统计负数的个数cnt = 0for x in nums:if x == 0:return 0if x < 0:cnt += 1return -1 if cnt & 1 else 1

三、3046. 分割数组

1.遍历+哈希表。

class Solution:def isPossibleToSplit(self, nums: List[int]) -> bool:# 每一个元素最多只能出现2次# 遍历+哈希表# 时复O(n),空复O(101)hash_list = [0] * 101for x in nums:if hash_list[x] == 2:return Falsehash_list[x] += 1return True

2.排序+遍历

class Solution:def isPossibleToSplit(self, nums: List[int]) -> bool:# 每一个元素最多只能出现2次# 排序+遍历# 时复O(nlogn),空复O(1)nums.sort()flag = 0pre = nums[0]for i in range(1,len(nums)):if flag and nums[i] == pre:return Falseif nums[i] == pre:flag = 1    #出现两次标记为1else:flag = 0pre = nums[i]return True

3.Counter函数1。老忘记有这函数,来自灵神题解(. - 力扣(LeetCode))。

class Solution:def isPossibleToSplit(self, nums: List[int]) -> bool:# 每一个元素最多只能出现2次# Counter函数1return max(Counter(nums).values()) <= 2

4. Counter函数2。来自灵神题解。

class Solution:def isPossibleToSplit(self, nums: List[int]) -> bool:# 每一个元素最多只能出现2次# Counter函数2return all(x <= 2 for x in Counter(nums).values())

 四、1413. 逐步求和得到正数的最小值

遍历

class Solution:def minStartValue(self, nums: List[int]) -> int:# 遍历# 求出最小前n项和s = 0mins = inffor x in nums:s += xmins = min(mins, s)     #更新前n和最小值return 1 - mins if mins < 1 else 1

感谢你看到这里!一起加油吧! 

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

相关文章:

  • 【核弹级软安全事件】XZ Utils库中发现秘密后门,影响主要Linux发行版,软件供应链安全大事件
  • 【Linux在程序运行时打印调用栈信息(函数名,文件行号等)】
  • 9.包和工具【go】
  • 判断一个字符串是否是真实手机号:JavaScript
  • 3D检测:从pointnet,voxelnet,pointpillar到centerpoint
  • 使用canvas内置api完成图片的缩放平移和导出和添加提示
  • 数据结构——二叉树——堆
  • 算法学习——LeetCode力扣图论篇3(127. 单词接龙、463. 岛屿的周长、684. 冗余连接、685. 冗余连接 II)
  • 状态模式详解:管理对象状态的利器
  • 探索----------------阿里云
  • Tidb和MySQL性能简单测试对比
  • 2024.2.6力扣每日一题——魔塔游戏
  • C# OAuth单点登录的实现
  • AtCoder Beginner Contest 347 (ABCDEF题)视频讲解
  • 【vue2+antvx6】报错Cannot read properties of undefined (reading ‘toUpperCase‘)
  • 主流的开发语言、环境及其特点
  • Android知识 - 代码混淆ProGuard规则介绍
  • 【Linux的进程篇章 - 冯诺依曼的体系结构】
  • flask-(数据连接池的使用,定制命令,信号的使用,表关系的建立和查询)
  • 设计模式学习笔记 - 设计模式与范式 -行为型:2.观察者模式(下):实现一个异步非阻塞的EventBus框架
  • 数据挖掘|贝叶斯分类器及其Python实现
  • Linux文件(系统)IO(含动静态库的链接操作)
  • CI/CD实战-jenkins结合ansible 7
  • 内网渗透-(黄金票据和白银票据)详解(一)
  • 学习transformer模型-Dropout的简明介绍
  • 游戏引擎中的大气和云的渲染
  • 华为鲲鹏云认证考试内容有哪些?华为鲲鹏云认证考试报名条件
  • v3-admin-vite 改造自动路由,view页面自解释Meta
  • FIFO存储器选型参数,结构原理,工艺与注意问题总结
  • jvm高级面试题-2024