面试题40:数组中的逆序对
来源:互联网 发布:外置式网络打印服务器 编辑:程序博客网 时间:2024/06/09 14:55
题目:
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中逆序对的总数。
边界条件及异常:
数组为空,或只有一个元素
思路:
根据归并排序来做
时间复杂度:O(nlgn)
空间复杂度:O(n)
#include <iostream> #include <vector> #include <queue>#include <string> #include <stack> #include <algorithm> #include <hash_set> //for hashtable#include <hash_map>#include <unordered_map>#include <set>#include <ctime>using namespace std;int MergeAndCount(vector<int>nums,vector<int> ©, int start, int end){if (start == end) return 0;int length = (end - start) / 2;int left = MergeAndCount(nums, copy, start, start + length);int right = MergeAndCount(nums, copy, start + length + 1, end);int i = start + length; //初始化为前半段最后一个数字的下标int j = end;int indexInCopy = end;int count = 0;while (i >= start&&j >= start + length + 1){if (nums[i] > nums[j]){copy[indexInCopy--] = nums[i--];count += j - start - length;}else copy[indexInCopy--] = nums[j--];}//for (; i >= start; --i) copy[indexInCopy--] = nums[i];//for (; j >= start + length + 1; --j) copy[indexInCopy--] = nums[j];return left + right + count;}int InversePairs(vector<int> nums){int size = nums.size();if (size < 2) return 0;vector<int> copy(nums); //对副本进行排序int count = MergeAndCount(nums,copy, 0, size - 1);return count;}int main(){int arr[] = { 7, 6, 4, 5 };vector<int> nums(arr, arr + 4);cout << InversePairs(nums) << endl;return 0;}
0 0
- 面试题40:数组中的逆序对
- 面试题29:数组中的逆序对
- 面试题36:数组中的逆序对
- 数组中的逆序对(面试题 36)
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题 36: 数组中的逆序对
- 面试题36:数组中的逆序对
- 面试题36. 数组中的逆序对
- 程序员面试题——数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- [剑指offer][面试题36]数组中的逆序对
- hdoj1597find the nth digit
- 2016/01/04本周工作计划
- Apache Karaf开启ssl Https
- 值得推荐的android开源框架
- iOS webview get和post请求传值给链接的页面
- 面试题40:数组中的逆序对
- 计算机网络学习(四)——链路层
- Android开发总结笔记 自定义View的编写 3-8
- eclipse中选中字段,其他相同字段被覆盖的颜色修改
- Android:操作联系人
- Java获取视频的时长——日期时间处理
- iconfont.cn中字体图标的问题
- Android应用开发SharedPreferences存储数据的使用方法
- require.js的用法-阮一峰