-
前言:
关于几种基本的排序算法:https://www.cnblogs.com/onepixel/articles/7674659.html
关于归并排序的思路和流程及代码:https://www.cnblogs.com/chengxiao/p/6194356.html
https://baike.baidu.com/item/归并排序/1639015?fr=aladdin -
题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。
即输出P%1000000007 -
思路:一开始想的是直接挨个遍历就行了,在idea上跑了下代码还行,但是牛客上跑不了。我就说,不可能这么简单。原来是用归并排序做的,也是头一次学这个。其核心思想,四个字:###分而治之###。详情参考前言里面的两个链接
4.代码:(和归并排序相比,就多了个计数)
package cn.test35;
public class test {
public static void main(String[] args){
int[] a ={1,2,3,4,5,6,7,0};
Solution solution=new Solution();
System.out.println(solution.InversePairs(a));
}
}
class Solution {
int p=0;//计数
public int InversePairs(int [] array) {
int[] temp=new int[array.length];
division(array,0,array.length-1,temp);
return p%1000000007;
}
public void division(int[] array,int left,int right,int[] temp){
if(left<right){
int mid=(left+right)/2;
division(array,left,mid,temp);//往左一直分
division(array,mid+1,right,temp);//往右一直分
merge(array,left,mid,right,temp);//治之
}
}
public void merge(int[] arr,int left,int mid,int right,int[] temp){
int i=left;//左序列指针
int j=mid+1;//右序列指针
int t=0;//temp的指针
while(i<=mid&&j<=right){
//按从小到大的顺序排好
if(arr[i]<=arr[j]){
temp[t++]=arr[i++];
}else{
temp[t++]=arr[j++];
p=p+mid-i+1;
p=p%1000000007;//题目让取这个余数啊,但是后面给了个很大的数组,导致超了,所以每次在这里也取个模,缩小一下值
}
}
//将左边你的元素填充到temp里
while(i<=mid){
temp[t++]=arr[i++];
}
//将右边的元素填充到temp里
while(j<=right){
temp[t++]=arr[j++];
}
t=0;
//将temp中的元素拷贝到原数组中
while(left<=right){
arr[left++]=temp[t++];
}
}
}