【LeetCode】力扣刷题之路
题目(20240902~20240906)
面试题 10.01. 合并排序的数组
给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。
初始化 A 和 B 的元素数量分别为 m 和 n。
说明:
- A.length == n + m
示例:
输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
方法1:数组
from typing import List
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
A[m:] = B
A.sort()
return A
if __name__ == '__main__':
s = Solution()
# 面试题10.01.合并排序的数组 - 示例1
A = [1, 2, 3, 0, 0, 0]
m = 3
B = [2, 5, 6]
n = 3
res = s.merge(A, m, B, n)
print(res) # 输出:[1,2,2,3,5,6]
方法2:正向双指针
from typing import List
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
i, j = 0, 0
C = []
while i < m or j < n:
if i == m:
C.append(B[j])
j += 1
elif j == n:
C.append(A[i])
i += 1
elif A[i] < B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1
A = C
return A
if __name__ == '__main__':
s = Solution()
# 面试题10.01.合并排序的数组 - 示例1
A = [1, 2, 3, 0, 0, 0]
m = 3
B = [2, 5, 6]
n = 3
res = s.merge(A, m, B, n)
print(res) # 输出:[1,2,2,3,5,6]
方法3:逆向双指针
from typing import List
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
i, j = m - 1, n - 1
tail = m + n - 1
while i >= 0 or j >= 0:
if i == -1:
A[tail] = B[j]
j -= 1
elif j == -1:
A[tail] = A[i]
i -= 1
elif A[i] > B[j]:
A[tail] = A[i]
i -= 1
else:
A[tail] = B[j]
j -= 1
tail -= 1
return A
if __name__ == '__main__':
s = Solution()
# 面试题10.01.合并排序的数组 - 示例1
A = [1, 2, 3, 0, 0, 0]
m = 3
B = [2, 5, 6]
n = 3
res = s.merge(A, m, B, n)
print(res) # 输出:[1,2,2,3,5,6]
面试题01.04. 回文排列
给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。
回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。
回文串不一定是字典当中的单词。
示例 1:
输入:“tactcoa”
输出:true(排列有"tacocat"、“atcocta”,等等)
方法1:哈希表
from collections import defaultdict
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
dic = defaultdict(int)
for c in s:
dic[c] += 1
odd = 0
for val in dic.values():
if val % 2 == 1:
odd += 1
if odd > 1:
return False
return True
if __name__ == '__main__':
s = Solution()
# 面试题 01.04.回文排列 - 示例1
s_str = "tactcoa"
res = s.canPermutePalindrome(s_str)
print(res) # 输出:True(排列有"tacocat"、"atcocta",等等)
方法2:位运算
from collections import defaultdict
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
res = 0
for c in s:
# 异或运算,相同为0,不同为1,所以回文串res返回1否则0
res ^= 1 << ord(c)
# 回文串1和1的取反(0)and运算为0,返回True;否则0和0的取反(0)and运算为1,返回False
return res & (res - 1) == 0
if __name__ == '__main__':
s = Solution()
# 面试题 01.04.回文排列 - 示例1
s_str = "tactcoa"
res = s.canPermutePalindrome(s_str)
print(res) # 输出:True(排列有"tacocat"、"atcocta",等等)
方法3:栈和排序
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
s = sorted(s)
stack = []
for i in s:
if not stack or stack[-1] != i:
stack.append(i)
else:
stack.pop()
return len(stack) <= 1
if __name__ == '__main__':
s = Solution()
# 面试题 01.04.回文排列 - 示例1
s_str = "tactcoa"
res = s.canPermutePalindrome(s_str)
print(res) # 输出:True(排列有"tacocat"、"atcocta",等等)