二倍数对数组
给定一个长度为偶数的整数数组 arr,只有对 arr 进行重组后可以满足 “对于每个 0 <= i < len(arr) / 2,都有 arr[2 * i + 1] = 2 * arr[2 * i]” 时,返回 true;否则,返回 false。
来源:力扣(LeetCode)
AC代码
class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
temp = Counter(arr)
if temp[0] % 2 == 1:
return False
for x in sorted(temp, key=abs):
if temp[x] <= temp[2 * x]:
temp[2 * x] -= temp[x]
else:
return False
return True
本题主要是排序思考,以及Counter函数对列表进行计数,以及sorted函数的key方法