Problema
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.
Vincoli
0 ≤ length ≤ 200,000
Esempi
Input:
numbers = [2, 4, 1, 3, 5]
Output atteso:
expected = 3
Input:
std::vector<long long> numbers = {2, 4, 1, 3, 5};
Output atteso:
long long expected = 3;
Input:
long[] numbers = new long[] {2, 4, 1, 3, 5};
Output atteso:
long expected = 3;
Spiegazione
Out-of-order pairs: (2,1), (4,1), (4,3): 3 inversions.
Input:
numbers = [1, 2, 3]
Output atteso:
expected = 0
Input:
std::vector<long long> numbers = {1, 2, 3};
Output atteso:
long long expected = 0;
Input:
long[] numbers = new long[] {1, 2, 3};
Output atteso:
long expected = 0;
Spiegazione
Already sorted: 0 inversions.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
An inversion is counted when a left-side number stays larger than a right-side number during merging.
Suggerimento 2
Split the list recursively and count cross-pairs while merging sorted halves.
Suggerimento 3
Be careful with duplicates: equal values are not inversions, so the comparison direction matters.
Complessità attesa
O(n log n) time, O(n) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.