欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 1497. Check If Array Pairs Are Divisible by k (python)

程序员文章站 2022-03-23 18:21:13
...

题目

Leetcode 1497. Check If Array Pairs Are Divisible by k (python)

解法:

解析见注释

class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        # main idea: First, we only need to consider the remain of every numbers. Second, we find the match between remains and see if all teh remains can form a valid match pair
        count = collections.defaultdict(int)
        # only store the remain of each number divided by k
        for num in arr:
            count[num%k] += 1
        # if there is number with remain 0, then the number of 0 must be times of 2
        if 0 in count:
            if count[0]%2 != 0:
                return False
            # must delete the remain 0 element
            del count[0]
        
        # for the rest of the remains, the count of remain and count of k-remain must be equal
        for remain in count.keys():
            if count[remain] != count[k-remain]:
                return False
        return True