面试题51. 数组中的逆序对
思路一 暴力法
会超出时间限制!! 牛客中只能AC 50%
public class Solution {
public int InversePairs(int [] array) {
int count = 0;
for(int i = 0; i < array.length; i++){
for(int j = i+1; j < array.length; j++){
if (array[i] > array[j]) count++;
}
}
return count;
}
}
思路一 暴力法
复杂度
- 时间: O(NlogN)
- 空间: O(N)
public class Solution {
private int count = 0;
public int InversePairs(int [] array) {
if (array == null || array.length == 0) {
return 0;
}
mergeSort(array);
return count;
}
public void merge(int [] arr, int low, int high, int mid, int[] temp){
if(low >= high) return ;
int i = low;
int j = mid+1;
int p = low;
// 合 ---- 记录左右两边的位置。
while(i <= mid && j <= high){
if(i <= mid && arr[i] <= arr[j]){
temp[p++] = arr[i++];
}else{
temp[p++] = arr[j++];
count = (count + (mid - i +1)) % 1000000007 ;
}
}
while(i <= mid){
temp[p++] = arr[i++];
}
while (j <= high){
temp[p++] = arr[j++];
}
// 将temp中合并的结果拷贝到arr中
p = low;
while(low <= high){
arr[low++] = temp[p++];
}
}
// 分 -- 拆分为左右两个区间
public void merge_sort(int[] arr, int low, int high, int[] temp){
if(low < high){
int mid = (low + high) / 2;
merge_sort(arr, low, mid, temp);
merge_sort(arr, mid+1, high, temp);
merge(arr, low, high, mid, temp);
}
}
public void mergeSort(int[] arr){
int[] temp = new int[arr.length];
merge_sort(arr, 0, arr.length-1, temp);
}
}