PS/릿코드
[릿코드 1497] Check If Array Pairs Are Divisible by k (파이썬/python)
BLUE_ERASER
2023. 3. 8. 21:40
728x90
https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/description/
Check If Array Pairs Are Divisible by k - LeetCode
Can you solve this real interview question? Check If Array Pairs Are Divisible by k - Given an array of integers arr of even length n and an integer k. We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. R
leetcode.com
생각보다 아이디어가 안떠올라서 당황했다;
문제의 요지는 이렇다. 두 수를 더했을때 k로 나누어 떨어져야한다.
만약 두수 A B 가 있을때 (A를 k로 나눈 나머지 + B를 k로 나눈 나머지) == k여야한다.
엄청 하드코딩해서 코드가 매우 더럽다..
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
remainder_dic = {}
# 나머지를 딕셔너리에 저장
for a in arr:
num = remainder_dic.get(a % k, 0)
remainder_dic[a % k] = num + 1
for key, value in remainder_dic.items():
if value > 0:
pair_remainder = k - key
if pair_remainder == key:
if value % 2 == 0:
remainder_dic[key] = 0
continue
else:
return False
pair_remainder_cnt = remainder_dic.get(pair_remainder, 0)
if pair_remainder_cnt >= value:
remainder_dic[pair_remainder] = pair_remainder_cnt - value
remainder_dic[key] = 0
for key, value in remainder_dic.items():
if key == 0:
continue
if value > 0:
return False
return True
728x90