当前位置: 代码迷 >> 综合 >> Leetcode 1497. Check If Array Pairs Are Divisible by k (python)
  详细解决方案

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

热度:26   发布时间:2023-11-26 06:28:15.0

题目

在这里插入图片描述

解法:

解析见注释

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 paircount = collections.defaultdict(int)# only store the remain of each number divided by kfor num in arr:count[num%k] += 1# if there is number with remain 0, then the number of 0 must be times of 2if 0 in count:if count[0]%2 != 0:return False# must delete the remain 0 elementdel count[0]# for the rest of the remains, the count of remain and count of k-remain must be equalfor remain in count.keys():if count[remain] != count[k-remain]:return Falsereturn True
  相关解决方案