Đề bài
An inversion is a pair of positions i < j with numbers[i] > numbers[j]. Count all inversions. Lists can be long, so a merge-sort based O(n log n) count is needed.
Implement count_inversions(numbers).
Input
numbers: The list of integers.
Output
Return the number of inversions.
Ràng buộc
0 ≤ length ≤ 200,000
Ví dụ
Đầu vào:
numbers = [2, 4, 1, 3, 5]
Kết quả mong đợi:
expected = 3
Đầu vào:
std::vector<long long> numbers = {2, 4, 1, 3, 5};
Kết quả mong đợi:
long long expected = 3;
Đầu vào:
long[] numbers = new long[] {2, 4, 1, 3, 5};
Kết quả mong đợi:
long expected = 3;
Giải thích
Out-of-order pairs: (2,1), (4,1), (4,3): 3 inversions.
Đầu vào:
numbers = [1, 2, 3]
Kết quả mong đợi:
expected = 0
Đầu vào:
std::vector<long long> numbers = {1, 2, 3};
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long[] numbers = new long[] {1, 2, 3};
Kết quả mong đợi:
long expected = 0;
Giải thích
Already sorted: 0 inversions.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
An inversion is counted when a left-side number stays larger than a right-side number during merging.
Gợi ý 2
Split the list recursively and count cross-pairs while merging sorted halves.
Gợi ý 3
Be careful with duplicates: equal values are not inversions, so the comparison direction matters.
Độ phức tạp mong đợi
O(n log n) time, O(n) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.