面試題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);
}
}