数组中的逆序对-剑指Offer

数组中的逆序对

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

思路

  1. 如果扫描整个数组,每个数字跟后面的数字比较大小,整体的复杂度是O(n^2)
  2. 可以利用归并排序的算法的思想,在排序的同时判断前后两个子序列中存在的逆序对,都是从后往前排,如果前面的数大于后面的数,因为都是已经排好序的所以前面的数一定比后面的数都大,逆序对为后面剩下的元素的数量,然后正常排序;若小于,则这个元素不产生逆序对,正常排序。时间复杂度是O(nlogn)

代码

public class Solution {
    public int InversePairs(int [] array) { if (array == null || array.length == 0) { return 0; } int[] copy = new int[array.length]; for (int i = 0; i < array.length; i++) { copy[i] = array[i]; } int count = inverseCore(array, copy, 0, array.length - 1); return count; } public int inverseCore(int[] data, int[] copy, int start, int end) { if (start == end) { copy[start] = data[start]; return 0; } int length = (end - start) / 2; int left = inverseCore(copy, data, start, start + length); int right = inverseCore(copy, data, start + length + 1, end); int i = start + length; int j = end; int indexCopy = end; int count = 0; while (i >= start && j >= start + length + 1) { if (data[i] > data[j]) { copy[indexCopy--] = data[i--]; count += j - (start + length); } else { copy[indexCopy--] = data[j--]; } } for (; i >= start; i--) { copy[indexCopy--] = data[i]; } for (; j >= start+length+1; j--) { copy[indexCopy--] = data[j]; } return count + left + right; } }

转载于:https://www.cnblogs.com/rosending/p/5644986.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值