好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java简单实现数组中的逆序对

题目描述:

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数p。并将p对1000000007取模的结果输出。 即输出p%1000000007

解题思路:

一开始一头雾水,后面想到了使用归并排序的思想,其实有多少个逆序对,就是归并排序的时候,后面的数要超越前面多少个,嗯,好像不是很好说,要不然直接看代码吧。还要注意,题目当中说要输出取模的结果,这说明数据可能非常大,所以如果只是单纯的在最后取模的话可能还是无法避免数据太大的影响,所以我们在每次更新count的时候就对其进行取模运算。

刚好又练习了一遍归并排序,记录一下

?

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

public class solution {

   int count;

   public int inversepairs( int [] array) {

     count = 0 ;

     if (array != null ){

       divpairs(array, 0 , array.length- 1 );

     }

     return count% 1000000007 ;

   }

  

   public void divpairs( int [] array, int start, int end){

     if (start >= end)

       return ;

     int mid = (start + end)>> 1 ;

     divpairs(array, start, mid);

     divpairs(array, mid+ 1 , end);

    

     mergepairs(array, start, mid, end);

   }

  

   public void mergepairs( int [] array, int start, int mid, int end){

     int i = start, j = mid+ 1 , k = 0 ;

     int [] temp = new int [end-start+ 1 ];

     while (i <= mid && j <= end){

       if (array[i] <= array[j]){

         temp[k++] = array[i++];

       } else {

         temp[k++] = array[j++];

         count += mid - i + 1 ;

         count %= 1000000007 ;

       }

     }

     while (i <= mid){

       temp[k++] = array[i++];

     }

     while (j <= end){

       temp[k++] = array[j++];

     }

     for ( int x = 0 ; x < temp.length; x++){

       array[start+x] = temp[x];

     }

   }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/zz0129/article/details/81321778

查看更多关于java简单实现数组中的逆序对的详细内容...

  阅读:16次