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

2025-05-29 0 74

题目描述:

数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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];

}

}

}

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

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java简单实现数组中的逆序对 https://www.kuaiidc.com/109867.html

相关文章

发表评论
暂无评论