Leetcode 1497. Check If Array Pairs Are Divisible by k (python)
程序员文章站
2022-03-23 18:21:13
...
题目
解法:
解析见注释
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
上一篇: 雾霾天孩子咳嗽怎么办?
下一篇: 50:pow(x,n)