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

本文介绍了如何通过模拟、数学公式、前缀和等方法在LeetCode题目中计算区间内奇数数量,以及如何用遍历、哈希表、排序和PythonCounter函数处理数组元素积的符号、分割数组和逐步求和问题,寻找满足条件的最小值。
摘要由CSDN通过智能技术生成

一、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) // 2
        return pre_odd(high) - pre_odd(low - 1)

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

遍历

class Solution:
    def arraySign(self, nums: List[int]) -> int:
        # 遍历
        # 有0为0,无0统计负数的个数
        cnt = 0
        for x in nums:
            if x == 0:
                return 0
            if x < 0:
                cnt += 1
        return -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] * 101
        for x in nums:
            if hash_list[x] == 2:
                return False
            hash_list[x] += 1
        return True

2.排序+遍历

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

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

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

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

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

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

遍历

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值