|
|
我网上找到了solution,但是看不懂
- void update(int idx, std::vector<int>&tree, int n) {
- while (idx <= n) {
- tree[idx] ++;
- auto t = idx&-idx;
- idx += t;
- }
- }
- int query(int idx, std::vector<int>&tree) {
- int ans = 0;
- while (idx != 0) {
- ans += tree[idx];
- idx -= (idx&-idx);
- }
- return ans;
- }
- //O(n*logn)
- int number_of_swaps_to_sort(std::vector<int> nums) {
- int n = nums.size();
- //It works if numbers are unique
- //first compress the values keeping the order, example [10, 4, 8 , 5] -> [4,1,3,2]
- std::vector<int>aux = nums;
- sort(aux.begin(), aux.end());
- std::unordered_map<int, int>ranking;
- for (int i = 0; i < n; i++) ranking[aux[i]] = i + 1;
- for (int i = 0; i < n; i++) nums[i] = ranking[nums[i]];
- //[4, 1,3 ,2] for each value, count number of elements on right side which are smaller than it.
- //we can use binary indexed trees
- std::vector<int>tree(n + 1, 0);
- int ans = 0;
- for (int i = n - 1; i >= 0; i--) {
- update(nums[i], tree, n);
- ans += query(nums[i] - 1, tree);
- }
- return ans;
- }
复制代码
|
|