面试题36—数组中的逆序对
来源:互联网 发布:靠谱泰国代购淘宝 知乎 编辑:程序博客网 时间:2024/06/16 09:17
**题目:在数组中的两个数如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。求一个数组的逆序对的总数。
代码示例:**
#include<iostream>using namespace std;int Merge2(int a[], int low, int mid, int high)//二路归并算法{ int InverseNum = 0; int i = low; int j = mid + 1; int k = 0; int *temp = new int[high - low + 1]; while (i <= mid&&j <= high) { if (a[i] <= a[j]) { temp[k] = a[i]; i++; k++; } else { for (int h = i; h <= mid;h++) cout << "逆序对:" << a[h] << " " << a[j] << endl; InverseNum += mid - i + 1; temp[k] = a[j]; k++; j++; } } while (i <= mid) { temp[k] = a[i]; i++; k++; } while (j <= high) { temp[k] = a[j]; k++; j++; } // for (int k = 0; k < high-low + 1; k++) { a[low + k] = temp[k]; } delete temp; return InverseNum;}int MergePass2(int a[], int n, int len){ int InverseNum = 0; int i; for (i = 0; i + 2*len - 1 < n; i = i + 2 * len) { InverseNum += Merge2(a, i, i + len - 1, i + 2 * len - 1); } if (i+len-1<n) InverseNum += Merge2(a, i, i + len - 1, n - 1); return InverseNum;}int CountInverseNum(int a[], int n){ if (n <= 1 || a == NULL) return -1; int InverseNum = 0; int len = 1; for (; len < n; len = len * 2) { InverseNum += MergePass2(a, n, len); } return InverseNum;}int main(){ const int n = 8; int a[n] = { 5,4,3,3,3,3,2,1}; cout << "原数组:"; for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl << endl; int InverseNum = 0; InverseNum = CountInverseNum(a, n); cout << endl<<"逆序对数:" << InverseNum << endl;}
阅读全文
0 0
- 面试题36:数组中的逆序对
- 数组中的逆序对(面试题 36)
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题 36: 数组中的逆序对
- 面试题36:数组中的逆序对
- 剑指offer 面试题36—数组中的逆序对
- 面试题36—数组中的逆序对
- 面试题29:数组中的逆序对
- 面试题40:数组中的逆序对
- 面试题36. 数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- 实例探索Java模式之路——门面模式
- 【NOIP2017模拟6.26】下蛋爷
- 九度1089:数字反转
- PhpStorm中,解决ThinkPHP没有代码提示的问题
- nodeJs安装及常见问题
- 面试题36—数组中的逆序对
- 用注解配置ssh
- 实训笔记第二天
- 异步请求调用
- Android定时器
- 面试题37—两个链表的第一个公共结点
- Unable to satisfy the following requirements解决方案
- Android性能优化之巧用软引用与弱引用优化内存使用
- 获取过度颜色百分比及设置背景颜色渐变