在數組中的兩個數字,如果前面一個數字大于后面的數字,則這兩個數字組成一個逆序對,例如在數組{7,5,6,4}中,一共存在5對逆序對,分別是{7,6},{7,5},{7,4},{6,4},{5,4}。輸入一個數組,求出這個數組中的逆序對的總數p。并將p對1000000007取模的結果輸出。,即輸出p%1000000007。
代碼
解法一
暴力簡單低效,不會改變原數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static int inversepairs( int [] array) { if (array == null || array.length < 2 ) { return 0 ; } 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 % 1000000007 ; } |
解法二
利用數組的歸并排序,高效,但是會改變原數組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
public static int inversepairs2( int [] array) { if (array == null || array.length < 2 ) { return 0 ; } int count = mergesort(array, 0 , array.length - 1 ); return count % 1000000007 ; } private static int mergesort( int [] array, int start, int end) { if (start >= end) { return 0 ; } // 找到數組的中點,分割為兩個子數組,遞歸求解 int middle = (start + end) / 2 ; int left = mergesort(array, start, middle); int right = mergesort(array, middle + 1 , end); // 存儲歸并后的數組 int [] copy = new int [array.length]; system.arraycopy(array, start, copy, start, end - start + 1 ); // 從兩個子數組的尾部開始遍歷 int i = middle; int j = end; int copyindex = end; // 記錄逆序對的數量 int count = 0 ; while (i >= start && j >= middle + 1 ) { // 數組是升序的 // 如果左邊數組比右邊數組大,則將大的放入存儲數組中 // 并且累加逆序對,應為是有序的,所以左邊數組的第i個元素比第j個及其之前的數都大 if (array[i] > array[j]) { copy[copyindex--] = array[i--]; count += (j - middle); } else { copy[copyindex--] = array[j--]; } } // 將子數組剩余的部分一次寫入歸并后的存儲數組 while (i >= start) { copy[copyindex--] = array[i--]; } while (j >= middle + 1 ) { copy[copyindex--] = array[j--]; } // 將本次兩個子數組的合并寫入原數組中 for ( int k = start; k <= end ; k++) { array[k] = copy[k]; } return left + right + count; } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zl18310999566/article/details/80228859