树状数组求逆序对
class Solution { public int reversePairs(int[] nums) { int l = nums.length; int []tmp = new int[l];//l就可以 System.arraycopy(nums,0,tmp,0,l); Arrays.sort(tmp);
//离散化 for(int i=0;i<l;i++){ nums[i] = Arrays.binarySearch(tmp,nums[i])+1; } int ret =0; BIT bit =new BIT(l); for(int i=0;i<l;i++){ bit.update(nums[i],1); ret+=(bit.getsum(l)-bit.getsum(nums[i])); } return ret; } } class BIT { private int n; private int[]c ; public BIT(int n){ this.n = n; this.c =new int[n+1]; } int lowbit(int x){ return x&(-x); } void update(int i,int num){ while(i<=n){ c[i]+=num; i+=lowbit(i); } } int getsum(int i){ int sum =0; while(i>0){ sum+=c[i]; i-=lowbit(i); } return sum; } }