剑指Offer-51:数组中的逆序对
2018-03-15 11:37
381 查看
题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。例子:
如在数组{7,5,6,4}中,一共存在5个逆序对,分别是(7,6)、(7,5)、(7,4)、(6,4)、(5,4)。链接:
剑指Offer(第2版):P249思路标签:
算法:空间换时间、归并排序解答:
时间复杂度O(nlogn),空间复杂度O(n)
使用归并排序的思想,求每个子数组的逆序对;先把数组分割成子数组,统计出子数组内部的逆序对的数目;
然后统计出两个相邻子数组之间的逆序对的数目;
在统计过程中,同时对数组进行排序。
需要一个辅助空间,来和原数组进行协同保存每个合并子数组的排序。
注意递归中传入参数copy和data互换。
class Solution { public: int InversePairs(vector<int> data) { int length = data.size(); if (length <= 0) return 0; vector<int> copy; for (int i = 0; i<length; ++i) copy.push_back(data[i]); long long count = InversePairsCore(data, copy, 0, length - 1); return count % 1000000007; } long long InversePairsCore(vector<int> &data, vector<int> ©, int start, int end) { if (start == end) { copy[start] = data[start]; return 0; } int length = (end - start) / 2; long long left = InversePairsCore(copy, data, start, start + length); long long right = InversePairsCore(copy, data, start + length + 1, end); int i = start + length; int j = end; int indexCopy = end; long long count = 0; while (i >= start && j >= start + length + 1) { if (data[i] > data[j]) { copy[indexCopy--] = data[i--]; count += j - start - length; } else { copy[indexCopy--] = data[j--]; } } for (; i >= start; --i) copy[indexCopy--] = data[i]; for (; j >= start + length + 1; --j) copy[indexCopy--] = data[j]; return count + left + right; } };
相关文章推荐
- 【剑指offer】面试题51:数组中的逆序对
- 20.剑指offer-数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指offer-数组中的逆序对-Java
- 剑指offer面试题36数组中的逆序对数
- 剑指offer-第五章优化时间和空间效率(数组中的逆序对的总数)
- 剑指offer面试题36:数组中的逆序对
- 剑指offer: 数组中的逆序对
- 剑指offer 编程题(34):数组中的逆序对
- 剑指Offer_51 求逆序对数
- 【剑指offer】数组中的逆序对
- 【剑指offer】面试题36:数组中的逆序对
- 剑指Offer 面试题36:数组中的逆序对及其变形(Leetcode 315. Count of Smaller Numbers After Self)题解
- 剑指offer-5-面试36:数组中的逆序对(时间效率和空间效率的平衡)
- 【剑指offer】数组中的逆序对
- 剑指offer-面试题51:数组中重复的数字
- [剑指OFFER] 数组中的逆序对
- 【剑指Offer面试编程题】题目1348:数组中的逆序对--九度OJ
- 剑指Offer----面试题36:数组中的逆序对
- 剑指Offer_51_构建乘积数组