题目:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P mod 1000000007
数据范围: 对于 50% 的数据, size≤10^4
对于 100% 的数据, size≤10^5
数组中所有数字的值满足 0≤val≤1000000
要求:空间复杂度 O(n),时间复杂度 O(nlogn)
输入描述:
题目保证输入的数组中没有的相同的数字
示例1
输入:[1,2,3,4,5,6,7,0]
返回值:7
示例2
输入:[1,2,3]
返回值:0
public class Solution {
public int InversePairs(int [] array) {
long count = 0;
int insertVal;
int index;
for(int i = 1; i < array.length; i++) {
insertVal = array[i];
index = i - 1;
while(index >= 0 && insertVal < array[index]) {
count++;
array[index + 1] = array[index];
index--;
}
array[++index] = insertVal;
}
return (int)(count % 1000000007);
}
}