假设我们有一个名为nums的数组。我们必须检查是否有可能重新排列num的元素,使其符合条件-
因此,如果输入像nums = [8,-4,4,-8],那么输出将为True,就好像我们为i = 0排列像[-4,-8,4,8]这样的数组一样,对于i = 1,nums [2 * 0 +1] = 2 *(-4)= -8 nums [2 * 1 +1] = 2 * 4 = 8
让我们看下面的实现以更好地理解-
from collections import defaultdict def solve(nums): freq = defaultdict(int) for item in nums: freq[item] += 1 for item in sorted(nums, key = abs): if freq[item] == 0: continue if freq[2 * item] == 0: return False freq[item] -= 1 freq[2 * item] -= 1 return True nums = [8, -4, 4, -8] print(solve(nums))
[8, -4, 4, -8]输出结果
True