剑指offer之面试题36数组中的逆序对
来源:互联网 发布:树莓派怎样编程 编辑:程序博客网 时间:2024/05/29 03:09
问题描述:
在数组中的两个数字如果前面的一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
实现代码如下:
#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <limits.h>int doFindInverseCount(int *date,int *copy,int left,int right){if(left==right){copy[left]=date[left];return 0;}int len = (right-left)/2;int leftcount = doFindInverseCount(date,copy,left,left+len);int rightcount = doFindInverseCount(date,copy,left+len+1,right);int leftPosition=left+len;int rightPosition=right;int indexCopy = right;int count = 0;while(leftPosition>=left && rightPosition>=left+len+1){if(date[leftPosition]>date[rightPosition]){copy[indexCopy--]=date[leftPosition--];count+=rightPosition-left-len;}else{copy[indexCopy--]=date[rightPosition--];}}for(;leftPosition>=left;leftPosition--){copy[indexCopy--]=date[leftPosition--];}for(;rightPosition>=left+len+1;rightPosition--){copy[indexCopy--]=date[rightPosition--];}int i;for(i=left;i<=right;i++){date[i]=copy[i];}return leftcount + count + rightcount;}int findInverseCount(int *date,int len){if(date==NULL || len <=0)return 0;int *copy = (int *)malloc(sizeof(int)*len);int count = doFindInverseCount(date,copy,0,len-1);return count;}int main(int argc, char *argv[]){int date[]={7,5,6,4};int len= sizeof(date)/sizeof(int);int rs = findInverseCount(date,len);printf("%d\n",rs);return 0;}
上面算法的时间复杂度是O(nlgn),空间复杂度是O(n)。
所以上面是用空间换时间的算法。
参考资料:
剑指offer
备注:
转载请注明出处:http://blog.csdn.net/wsyw126/article/details/51383887
作者:WSYW126
0 0
- 剑指offer之面试题36数组中的逆序对
- 剑指Offer之面试题36:数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- [剑指offer][面试题36]数组中的逆序对
- 【剑指offer】面试题36:数组中的逆序对
- 剑指Offer:面试题36 数组中的逆序对
- 剑指offer 面试题36:数组中的逆序对
- 剑指offer 面试题36—数组中的逆序对
- 【剑指Offer学习】【面试题36:数组中的逆序对】
- 剑指offer-面试题36:数组中的逆序对
- 剑指offer面试题36-数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- 剑指Offer----面试题36:数组中的逆序对
- 剑指Offer面试题36:数组中的逆序对
- 剑指offer--面试题36:数组中的逆序对
- 剑指Offer---面试题36:数组中的逆序对
- 【剑指offer】面试题36-数组中的逆序对
- 剑指offer-面试题36-数组中的逆序对
- 程序员装逼指南
- orace后台执行
- 图表控件,官方AchartEngine控件学习
- 代码块的隐藏
- jQuery:this与$(this)的差別
- 剑指offer之面试题36数组中的逆序对
- bzoj 3822: 文学 动态规划
- apache + httpclient4 + jsoup 进行模拟浏览器url访问
- Systemd 入门教程:实战篇
- CentOS7中安装subversion
- JS中数组去重及求量数组中的相同字符个数
- 苏宁易购亿万级商品评价系统的架构演进之路和实现细节
- MAKEWORD
- mac 系统不区分大小写,linux 服务器区分大小写