LeetCode 954 Array of Doubled Pairs (Python)

Posted by 小明MaxMing on August 11, 2021

题目

Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.

解题思路

贪心,使用计数器求出每个数出现的次数,然后按绝对值从小到大,如果当前数为n,查看2n出现的次数是否大于等于n

代码

class Solution:
    def canReorderDoubled(self, arr: List[int]) -> bool:
        ct = collections.Counter(arr)
        for n in sorted(ct, key=abs):
            if ct[n] > ct[2 * n]:
                return False
            ct[2 * n] -= ct[n]
        return True

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅