[HackerRank][Python3] Merge Sort: Counting Inversions
2018. 7. 22. 23:42 |
프로그래밍/HackerRank
Problem :
https://www.hackerrank.com/challenges/ctci-merge-sort/problem
My Solution :
#!/usr/bin/env python3 def countInversions(arr, left, right): count = 0 if right - left < 2: return count middle = (right + left) // 2 left_count = countInversions(arr, left, middle) right_count = countInversions(arr, middle, right) count += left_count + right_count merged = [] i, j = left, middle while i < middle and j < right: if arr[i] > arr[j]: merged.append(arr[j]) j += 1 count += middle - i else: merged.append(arr[i]) i += 1 if i == middle: merged += arr[j:right] else: merged += arr[i:middle] arr[left:right] = merged return count t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().rstrip().split())) result = countInversions(arr, 0, n) print(result)
'프로그래밍 > HackerRank' 카테고리의 다른 글
[HackerRank][Python3] Tries: Contacts (0) | 2018.08.05 |
---|---|
[HackerRank][Python3] Swap Nodes [Algo] (0) | 2018.07.27 |
[HackerRank][Python3] Special Palindrome Again (0) | 2018.07.23 |
[HackerRank][Python3] Fraudulent Activity Notifications (0) | 2018.07.23 |
[HackerRank][Python3] Roads and Libraries (0) | 2018.07.22 |
[HackerRank][Python3] BFS: Shortest Reach in a Graph (0) | 2018.07.22 |
[HackerRank][Python3] Find the nearest clone (0) | 2018.07.22 |
[HackerRank][Python3] DFS: Connected Cell in a Grid (0) | 2018.07.21 |
최근에 달린 댓글 최근에 달린 댓글