24数媒Java上机2

对于一个包含N个非负整数的数组A[0..n-1],如果有0<=i < j<n,且A[ i ]>A[ j ],则称(A[ i] ,A[ j] )为数组A中的一个逆序对。

现给定一组数,请你算出这组数中共有多少组逆序对。

输入格式:

共两行,第一行是一个整数N(N≤1000),表示这组数的个数。第二行有N个整数,用空格分隔,为这组数。测试用例保证合法且所有数均可以用int存储。

输出格式:

只有一行,为一个整数,代表这组数中逆序对的数量。

输入样例:

5

3 1 4 5 2

输出样例:

4

分析:

1、朴素解法:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         int n = sc.nextInt();  
 7         int[] array = new int[n];
 8         for (int i = 0; i < n; i++) {
 9             array[i] = sc.nextInt();
10         }
11 
12         int count = 0; 
13 
14         for (int i = 0; i < n; i++) {
15             for (int j = i + 1; j < n; j++) {
16                 if (array[i] > array[j]) {
17                     count++;
18                 }
19             }
20         }
21 
22         System.out.println(count);
23 
24         sc.close();
25     }
26 }

时间复杂度O(n2)

2、归并排序

 1 import java.util.Scanner;
 2 
 3 public class nixu {
 4     public static void main(String[] args) {
 5         Scanner scanner = new Scanner(System.in);
 6         int n = scanner.nextInt();
 7         int[] numbs = new int[n];
 8         for (int i = 0; i < n; i++) {
 9             numbs[i] = scanner.nextInt();
10         }
11         System.out.println(countInversions(numbs));
12     }
13 
14     public static int countInversions(int[] numbs) {
15         return mergeSort(numbs, 0, numbs.length - 1);
16     }
17 
18     private static int mergeSort(int[] nums, int left, int right) {
19         if (left >= right) return 0;
20         int mid = left + (right - left) / 2;
21         int count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);
22         int[] temp = new int[right - left + 1];
23         int i = left, j = mid + 1, k = 0;
24         while (i <= mid && j <= right) {
25             if (nums[i] <= nums[j]) {
26                 temp[k++] = nums[i++];
27             } else {
28                 temp[k++] = nums[j++];
29                 count += mid - i + 1;
30             }
31         }
32         while (i <= mid) temp[k++] = nums[i++];
33         while (j <= right) temp[k++] = nums[j++];
34         System.arraycopy(temp, 0, nums, left, temp.length);
35         return count;
36     }
37 }

时间复杂度O(nlogn)

posted @ 2024-04-26 12:26  jiayusu  阅读(3)  评论(0编辑  收藏  举报