剑指 Offer 51. 数组中的逆序对
难度:困难
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
限制:
0 <= 数组长度 <= 50000
解答:
class BIT{
private int[] tree;
private int n;
public BIT(int n){
this.n = n;
this.tree = new int[n + 1];
}
public static int lowbit(int x){
return x & (-x);
}
public int query(int x){
int ans = 0;
while(x != 0){
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
public void update(int x){
while(x <= n){
tree[x]++;
x += lowbit(x);
}
}
}
class Solution {
//离散化树状数组
//时间复杂度:O(NlogN)。空间复杂度:O(N)
public int reversePairs(int[] nums) {
int n = nums.length;
int[] temp = new int[n];
System.arraycopy(nums, 0, temp, 0, n);
Arrays.sort(temp);
for(int i = 0; i < n; i++){
nums[i] = Arrays.binarySearch(temp, nums[i]) + 1;
}
BIT bit = new BIT(n);
int ans = 0;
for(int i = n - 1; i >= 0; i--){
ans += bit.query(nums[i] - 1);
bit.update(nums[i]);
}
return ans;
}
}
class Solution {
//归并排序
//时间复杂度:O(NlogN)。空间复杂度:O(N)
int[] nums, temp;
public int reversePairs(int[] nums) {
this.nums = nums;
temp = new int[nums.length];
return mergeSort(0, nums.length - 1);
}
public int mergeSort(int left, int right){
if(left >= right) return 0;
int mid = (left + right) / 2;
int ans = mergeSort(left, mid) + mergeSort(mid + 1, right);
int i = left, j = mid + 1;
for(int k = left; k <= right; k++){
temp[k] = nums[k];
}
for(int k = left; k <= right; k++){
if(i == mid + 1)
nums[k] = temp[j++];
else if(j == right + 1 || temp[i] <= temp[j])
nums[k] = temp[i++];
else{
nums[k] = temp[j++];
ans += mid - i + 1;
}
}
return ans;
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/jian-zhi-offer-51-shu-zu-zhong-de-ni-xu-pvn2h/
https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/shu-zu-zhong-de-ni-xu-dui-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。