剑指offer_数组中的逆序对
2016-10-05 13:38
190 查看
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007.
解题思路:
这题目在于测试用例数组超大,不能也不用取余输出啊。
首先想到排序,因为如果存在逆序对,在升序排序中,总要做点什么对吧。
因为数组超大,想到 递归、分治。快排?归并?堆排?
归并才是这题的真解,归并排序的改进,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),
合并数组,合并时,出现前面的数组值array[i]大于后面数组值array[j]时;则前面数组array[i]~array[mid]都是大于array[j]的,count += mid+1 - i
注意:
这题目的数组超大,在记录返回值时候看,请使用float!!!每次返回之前先求余。。。(因为这问题,耽搁了许久。。。。坑)
上代码:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007.
解题思路:
这题目在于测试用例数组超大,不能也不用取余输出啊。
首先想到排序,因为如果存在逆序对,在升序排序中,总要做点什么对吧。
因为数组超大,想到 递归、分治。快排?归并?堆排?
归并才是这题的真解,归并排序的改进,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),
合并数组,合并时,出现前面的数组值array[i]大于后面数组值array[j]时;则前面数组array[i]~array[mid]都是大于array[j]的,count += mid+1 - i
注意:
这题目的数组超大,在记录返回值时候看,请使用float!!!每次返回之前先求余。。。(因为这问题,耽搁了许久。。。。坑)
上代码:
public class Solution { public int InversePairs(int [] array) { if(array==null||array.length==0){ return -1; } int[] temp= new int[array.length]; long res=getResult(array,temp,0,array.length-1); return (int)res%1000000007; } public long getResult(int[] array,int[] temp,int begin,int end){ if(end<=begin){ return 0; } int mid = (begin+end)/2; long left=getResult(array,temp,begin,mid); long right=getResult(array,temp,mid+1,end); long count= build(array,temp,begin,end); return count=(count+right+left)%1000000007; } public long build(int[] array,int[] temp,int begin,int end){ int mid=(begin+end)/2; int i=begin; int j=mid+1; long count=0; int te=begin; 4000 while(i<=mid&&j<=end){ if(array[i]<array[j]){ temp[te++]=array[i++]; }else{ temp[te++]=array[j++]; count+=(mid-i+1)%1000000007; } } while(i<=mid){ temp[te++]=array[i++]; } while(j<=end){ temp[te++]=array[j++]; } for(i=begin;i<=end;i++){ array[i]=temp[i]; } return count%1000000007; } }
相关文章推荐
- 【剑指offer】【九度oj】数组中的逆序对
- 剑指offer-数组中的逆序对
- 剑指offer-数组中的逆序对
- 剑指offer-36-数组中的逆序对
- 剑指Offer 面试题36:数组中的逆序对及其变形(Leetcode 315. Count of Smaller Numbers After Self)题解
- 剑指offer之面试题36:数组中的逆序对-归并排序的应用
- 20.剑指offer-数组中的逆序对
- 求数组中的逆序对的数量----剑指offer36题
- [剑指offer] 数组中的逆序对
- 剑指offer:数组中的逆序对
- (C++)剑指offer-35:数组中的逆序对(时间空间效率的平衡)(未完成)
- 剑指OFFER_求数组中逆序对的个数
- 剑指offer——面试题36:数组中的逆序对
- 【剑指Offer学习】【面试题36:数组中的逆序对】
- 【剑指offer】面试题51:数组中的逆序对
- 剑指offer 面试题36 数组逆序对个数
- 剑指offer之面试题36数组中的逆序对
- 剑指offer 面试题36:数组中的逆序对
- 剑指Offer----面试题36:数组中的逆序对
- 剑指offer——面试题36:数组中的逆序对