1.排序+双指针。我以为遍历时复很高,所以用的双指针。
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
#排序+双指针
nums1.sort()
nums2.sort()
ans = [[],[]]
a,b,n1,n2 = 0,0,len(nums1),len(nums2)
while a<n1 and b<n2:
x = nums1[a]
y = nums2[b]
if a > 0 and nums1[a-1] == x:
a += 1
continue
if b > 0 and nums2[b-1] == y:
b += 1
continue
if x > y:
ans[1].append(y)
b += 1
elif x < y:
ans[0].append(x)
a += 1
else:
a += 1
b += 1
# 将剩余存入
while a < n1:
x = nums1[a]
if a <= 0 or nums1[a-1] != x:
ans[0].append(x)
a += 1
while b < n2:
y = nums2[b]
if b <= 0 or nums2[b-1] != y:
ans[1].append(y)
b += 1
return ans
2.集合求差。来自题解(. - 力扣(LeetCode))。
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
# 集合差集
return [list(set(nums1)-set(nums2)),list(set(nums2)-set(nums1))]
下段来自chatgpt:
需要注意的是,集合操作的时间复杂度通常是接近 O(1) 的,因为集合内部使用哈希表实现,能够快速进行元素的查找和插入,但在极端情况下可能会达到 O(n)(例如哈希冲突较多的情况)。
3.集合差集+海象运算符。来自题解(. - 力扣(LeetCode))。
class Solution:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
# 集合差集+海象运算符
return [list((s1 := set(nums1)) - (s2 := set(nums2))),list(s2 - s1)]
下段来自chatgpt:
海象运算符的主要作用是可以在表达式中将计算结果赋值给变量,且在同一表达式中使用这个变量。这样可以避免重复计算相同的表达式,使代码更加简洁和易读。
1.排序
class Solution:
def buyChoco(self, prices: List[int], money: int) -> int:
# 排序
prices.sort()
s = prices[0] + prices[1]
return money - s if money >= s else money
2.遍历,求最小和次小。
class Solution:
def buyChoco(self, prices: List[int], money: int) -> int:
# 遍历,求最小和次小
a,b = inf,inf
for x in prices:
if x < a:
a,b = x,a
elif x < b:
b = x
return money - a - b if money >= a+b else money
1.遍历,时复O(n*m)。
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
# 遍历
# 分别求出每一行的最小值和每一列的最大值
# 出现相同元素即为幸运数,因为元素各不相同
minList,maxList = [inf]*len(matrix),[0]*len(matrix[0])
for i,row in enumerate(matrix):
for j,x in enumerate(row):
if x < minList[i]:
minList[i] = x
if x > maxList[j]:
maxList[j] = x
s1,s2 = set(minList),set(maxList)
return list(s1 - (s1 - s2))
参考官方题解方法二(. - 力扣(LeetCode)),对上述求最大小值列表部分代码进行修改。修改后如下:
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
# 遍历,时复O(n*m)
# 分别求出每一行的最小值和每一列的最大值
# 出现相同元素即为幸运数,因为元素各不相同
minList = [min(row) for row in matrix]
maxList = [max(col) for col in zip(*matrix)] #对matrix转置
s1,s2 = set(minList),set(maxList)
return list(s1 - (s1 - s2))
2.最小值中最大值和最大值中最小值,方法来自评论(. - 力扣(LeetCode))。时复O(n*m)。
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
# 最小值中最大值和最大值中最小值
minList = [min(row) for row in matrix]
maxList = [max(col) for col in zip(*matrix)] #对matrix转置
a,b = max(minList),min(maxList)
return [a] if a==b else []
完
感谢你看到这里!一起加油吧!