[HackerRank][Python3] Frequency Queries
2018. 7. 13. 02:36 |
프로그래밍/HackerRank
Problem :
https://www.hackerrank.com/challenges/frequency-queries/problem
My Solution :
#!/usr/bin/env python3 def solve(queries): count_dic = {} freq_dic = {} for case, data in queries: if case == 1: count = count_dic.setdefault(data, 0) freq = freq_dic.setdefault(count, 1) count_dic[data] += 1 freq_dic.setdefault(count+1, 0) freq_dic[count+1] += 1 freq_dic[count] -= 1 elif case == 2: count = count_dic.setdefault(data, 0) freq = freq_dic.setdefault(count, 1) if count > 0: count_dic[data] -= 1 freq_dic.setdefault(count-1, 0) freq_dic[count-1] += 1 freq_dic[count] -= 1 else: yield 1 if freq_dic.get(data, 0) > 0 else 0 q = int(input()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) for result in solve(queries): print(result)
My Solution2 :
동일한 풀이를 dictionary 대신 list로 처리해보려 하였으나 python 32비트에서 list 최대 size가 536,870,912 라서 10**9만큼 0으로 초기화 할 수 없었다. 대신 collections의 defaultdict로 코드 라인 수를 조금 줄여보았다.
#!/usr/bin/env python3 from collections import defaultdict def solve(queries): cnt = defaultdict(int) freq = defaultdict(int) for case, data in queries: if case == 1: cnt[data] += 1 freq[cnt[data]] += 1 freq[cnt[data]-1] -= 1 elif case == 2: if cnt[data] > 0: cnt[data] -= 1 freq[cnt[data]] += 1 freq[cnt[data]+1] -= 1 else: yield 1 if freq[data] > 0 else 0 q = int(input()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) for result in solve(queries): print(result)
'프로그래밍 > HackerRank' 카테고리의 다른 글
[HackerRank][Python3] Common Child (0) | 2018.07.15 |
---|---|
[HackerRank][Python3] Sherlock and the Valid String (0) | 2018.07.15 |
[HackerRank][Python3] Strings: Making Anagrams (0) | 2018.07.15 |
[HackerRank][Python3] Count Triplets (0) | 2018.07.13 |
[HackerRank][Python3] Sherlock and Anagrams (0) | 2018.07.12 |
[HackerRank][Python3] Array Manipulation (0) | 2018.07.09 |
[HackerRank][Python3] New Year Chaos (0) | 2018.07.07 |
[HackerRank][Python3] Minimum Swaps 2 (0) | 2018.07.06 |
최근에 달린 댓글 최근에 달린 댓글