数组中的逆序对
来源:互联网 发布:企业数据备份管理制度 编辑:程序博客网 时间:2024/06/08 10:46
求数组中的逆序对实际上有两种方法第一种直接暴力解决,两次循环,搞定,但是时间复杂度较高o(n^2),
另一种方法就是利用归并排序的方法,时间复杂度也就是归并排序的时间复杂度是O(N*lnN)时间紧迫直接上代码:
#include <iostream>;using namespace std;int InversePairsCore(int*arr,int start,int end,int*copy){ if(start>=end) { copy[start]=arr[start]; return 0; } int mid=(end+start)/2; int left=InversePairsCore(arr,start,mid,copy); int right=InversePairsCore(arr,mid+1,end,copy); int i=start; int j=mid+1; int index=start; int count=0; while(i<=mid&&j<=end) { if(arr[i]>arr[j]) { count=mid-i+1+count; copy[index]=arr[j]; ++j; } else{ copy[index]=arr[i]; ++i; } ++index; } while(i<=mid) { copy[index]=arr[i]; ++i; ++index; } while(j<=end) { copy[index]=arr[j]; ++j; ++index; } for(int i=start;i<=end;++i) arr[i]=copy[i]; return right+left+count;}int InversePairs(int *arr,int len){ if(!arr||len<=0) return 0; int *copy=new int[len]; for(int i=0;i<len;++i) copy[i]=arr[i]; int count=InversePairsCore(arr,0,len-1,copy); delete []copy; return count;}int main(){ int n; while(cin>>n) { int *arr=new int[n]; for(int i=0;i<n;++i) cin>>arr[i]; cout<<InversePairs(arr,n)<<endl; delete[]arr; } return 0;}
0 0
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 解决MySQL ERROR 1130 (HY000): Host 'XXXX' is not allowed to connect to this MySQL server
- vagrant 环境配置以及常用命令
- bzoj 2456: mode(找众数)
- 112. Path Sum
- redis的选择和定位
- 数组中的逆序对
- Test.java
- layer的layer.alert()自定义方法
- 防止点浏览器返回按钮,返回上一页的JS方法
- 5不可思议的旅游目的地参观
- oscache介绍
- C++中虚析构函数的作用
- Cocos[3.2]番外篇——获取本地时间
- 自定义流式布局FlowLayout