您的位置:首页 > 健康 > 养生 > 2024.6.10刷题记录

2024.6.10刷题记录

2024/10/13 23:49:10 来源:https://blog.csdn.net/lshx4658/article/details/139570045  浏览:    关键词:2024.6.10刷题记录

目录

一、881. 救生艇

贪心-排序-双指针

二、8. 字符串转换整数 (atoi)

1.模拟-未考虑溢出

2.考虑溢出问题

三、9. 回文数

1.双指针-字符串

2.数字翻转

3.数字翻转-只翻转一半


一、881. 救生艇

贪心-排序-双指针

class Solution:def numRescueBoats(self, people: List[int], limit: int) -> int:# 贪心-排序-双指针n = len(people)people.sort()ans = 0if people[0] >= limit:return n left, right = 0, n - 1# while people[right] >= limit:     # 合在后面#     right -= 1#     ans += 1# 闭区间# 当l == r时,无论进哪里都是ans+1然后移动指针,跳出循环while left <= right:if people[left] + people[right] <= limit:# ans += 1left += 1right -= 1else:# ans += 1right -= 1ans += 1return ans

二、8. 字符串转换整数 (atoi)

1.模拟-未考虑溢出

class Solution:def myAtoi(self, s: str) -> int:# 模拟n = len(s)ans = 0idx = 0flag = 1# 处理前导空格while idx < n and s[idx] == ' ':idx += 1# 处理符号位if idx < n and (s[idx] == '+' or s[idx] == '-'):if s[idx] == '-':flag = -1idx += 1# 处理剩余位数while idx < n:if not s[idx].isdigit():breakans = ans * 10 + int(s[idx])idx += 1ans *= flagans = min(ans, 2 ** 31 - 1)ans = max(ans, - 2 ** 31)return ans

2.考虑溢出问题

来自题解(. - 力扣(LeetCode)),优雅。

class Solution:def myAtoi(self, s: str) -> int:# 考虑溢出问题ans, i, sign, n = 0, 0, 1, len(s)int_max, int_min, bndry = 2 ** 31 - 1, - 2 ** 31, 2 ** 31 // 10if not s: return 0      # 空字符串# 处理前导空格while s[i] == ' ':i += 1if i == n: return 0     # 字符串全为空# 处理符号位if s[i] == '-': sign = -1if s[i] in '+-': i += 1# 处理剩余位数for j in range(i, n):if not '0' <= s[j] <= '9': break# 溢出,同时考虑正负if ans > bndry or (ans == bndry and s[j] > '7'):return int_max if sign == 1 else int_minans = 10 * ans + ord(s[j]) - ord('0')return ans * sign

三、9. 回文数

1.双指针-字符串

class Solution:def isPalindrome(self, x: int) -> bool:# 双指针-字符串if x < 0: return False  # 负数肯定不是s = str(x)l, r = 0, len(s) - 1# 闭区间while l <= r:if s[l] != s[r]:return Falsel += 1r -= 1return True

2.数字翻转

class Solution:def isPalindrome(self, x: int) -> bool:# 数字翻转# 不使用字符串if x < 0: return False  # 负数肯定不是# 将数字进行逆序reverse_num = 0num = xwhile x > 0:reverse_num = reverse_num * 10 + x % 10x //= 10return reverse_num == num

3.数字翻转-只翻转一半

来自官方题解(. - 力扣(LeetCode))。

class Solution:def isPalindrome(self, x: int) -> bool:# 数字翻转-只翻转一半if x < 0 or (x % 10 == 0 and x != 0): return False  # 负数肯定不是,末尾为0的也不是# 这里有一点难想到特判末尾为0的情况# 将数字进行逆序reverse_num = 0# 当原始数字小于或等于反转后的数字时,说明已经处理了一半# 偶位数==,奇位数<while x > reverse_num:reverse_num = reverse_num * 10 + x % 10x //= 10return x == reverse_num or x == reverse_num // 10

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com