題目描述:在數組中的兩個數字,若是前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個數組中的逆序對的總數。輸入: java
4 7 5 6 4樣例輸出:
5方法一:
掃描整個數組逐個數字比較該數字和前面數字的大小,因爲每一個數字都要和O(n)個數字作比較,所以這個算法的時間複雜度是O(n2)。 算法
import java.util.Scanner; /** * 數組中的逆序對 * 2014年3月15日 20:44:15 * @author aqia358 * */ public class MainLM { public static void count(int[] a){ long sum = 0; for(int i = 1; i < a.length; i++){ int j = i; while(j > 0){ if(a[j - 1] > a[i]) sum++; j--; } } System.out.println(sum); } public static void main(String[] args) { // int[] a = {7,5,6,4}; // int[] a = {9,8,7,6,5,4,3,2,1,0}; // MainLM.count(a); Scanner cin = new Scanner(System.in); while(cin.hasNext()){ int n = cin.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++){ a[i] = cin.nextInt(); } MainLM.count(a); } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; /** * 數組中的逆序對 * 2014年3月15日 20:44:15 * @author aqia358 * */ public class Main { public static long num = 0; public static int[] result; public static void merge(int[] a, int begin, int end){ if(begin != end){ int center = (begin+end)/2; merge(a, begin, center); merge(a, center+1, end); int i = begin; int left = begin; int right = center+1; while(left <= center && right <= end){ if(a[left] > a[right]){ result[i++] = a[right++]; num = num + center - left + 1;//最重要的一步 }else{ result[i++] = a[left++]; } } while(left <= center ){ result[i++] = a[left++]; } while(right <= end){ result[i++] = a[right++]; } for(int j = begin; j <= end; j++){ a[j] = result[j]; } } } public static void main(String[] args) throws IOException { // int[] a = {9,8,7,6,5,4,3,2,1,0}; // int[] a = {7,5,6,4}; // Main.merge(a, 0, a.length - 1); // System.out.println(Main.num); // Main.num = 0; StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(st.nextToken() != st.TT_EOF){ int m = (int) st.nval; int[] a = new int[m]; Main.result = new int[m]; for(int i = 0; i < m; i++){ st.nextToken(); a[i] = (int) st.nval; } Main.merge(a, 0, a.length - 1); System.out.println(Main.num); Main.num = 0; } } } /************************************************************** Problem: 1348 User: aqia358 Language: Java Result: Accepted Time:1270 ms Memory:43652 kb ****************************************************************/