给定两个大小分别为 m
和 n
的正序(从小到大)数组 nums1
和 nums2
。请你找出并返回这两个正序数组的中位数 。算法的时间复杂度应该为 O(log(m+n))
。
标签:数组,二分查找(目前不会)
代码:
2. 5——最长回文子串
给你一个字符串 s
,找到 s
中最长的回文子串。
标签:字符串,双指针
代码:
class Solution:
def longestPalindrome(self, s: str) -> str:
max_leng = len(s)
while max_leng:
left = 0
while left + max_leng <= len(s):
# left是左指针,left + max_leng是右指针
sub_s = s[left : left + max_leng]
if sub_s[::-1] == sub_s:
return sub_s
else:
left = left + 1
max_leng = max_leng - 1
3. 6——Z字形变换
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
请你实现这个将字符串进行指定行数变换的函数:string convert(string s, int numRows)。
标签:字符串
代码:
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1: # 行数为1,直接返回原字符串
return s
res = []
for i in range(numRows):
res.append("")
period = numRows + numRows - 2
i = 0
num = 0
for st in s:
res[i] = res[i] + st
num = num + 1
if 0 < (num % period) < numRows:
i = i + 1
else:
i = i - 1
return "".join(res)
4. 7——整数反转
给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 [−2^31, 2^31 − 1]
,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。
标签:数学
代码:
class Solution:
def reverse(self, x: int) -> int:
def x_len(x): # 求x的位数
leng = 0
while x:
leng = leng + 1
x = x // 10
return leng
def x_reverse(x, leng): # 求x的反转数
res = 0
while x:
x_end = x % 10
res = res + x_end * (10 ** (leng - 1))
x = x // 10
leng = leng - 1
return res
if x >= 0:
leng = x_len(x)
res = x_reverse(x, leng)
else:
leng = x_len(-x)
res = -x_reverse(-x, leng)
return res if -2**31 <= res <= 2**31 - 1 else 0
5. 8——字符串转换整数
给你一个 32 位的有符号整数 x
,返回将 x
中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 [−2^31, 2^31 − 1]
,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。
标签:数学(目前不会)
代码:
6. 9——回文数
给你一个整数 x
,如果 x
是一个回文整数,返回 true
;否则,返回 false
。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121
是回文,而 123
不是。
标签:数学
代码:
class Solution:
def isPalindrome(self, x: int) -> bool:
def x_len(x): # 求x的位数
leng = 0
while x:
leng = leng + 1
x = x // 10
return leng
def x_reverse(x, leng): # 求x的反转数
res = 0
while x:
x_end = x % 10
res = res + x_end * (10 ** (leng - 1))
x = x // 10
leng = leng - 1
return res
if x >= 0:
leng = x_len(x)
res = x_reverse(x, leng)
return res == x
else:
return False