• 剑指offer:数组中的逆序对


    题目描述:

    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。

    输入描述:

    题目保证输入的数组中没有的相同的数字

    数据范围:

    对于%50的数据,size<=10^4

    对于%75的数据,size<=10^5

    对于%100的数据,size<=2*10^5

    输入示例:

    1,2,3,4,5,6,7,0

    输出示例:

    7

    思路分析:

    1. 最直接的想法,对于每个数,向后依次比较,计算每个数的逆序对。这样的复杂度是O(n^2),需要优化。

    2. 利用空间换时间。利用归并排序的思想。参考:https://www.cnblogs.com/coffy/p/5896541.html,这样的时间复杂度就为O(nlogn)。

    代码:

     1 class Solution {
     2 public:
     3     int InversePairs(vector<int> data) {
     4         int length = data.size();
     5         if (length <= 0)
     6             return 0;
     7 
     8         vector<int> copy;
     9         for (int i = 0; i<length; ++i)
    10             copy.push_back(data[i]);
    11 
    12         long long count = InversePairsCore(data, copy, 0, length - 1);
    13         return count % 1000000007;
    14     }
    15 
    16     long long InversePairsCore(vector<int> &data, vector<int> &copy, int start, int end) {
    17         if (start == end) {
    18             copy[start] = data[start];
    19             return 0;
    20         }
    21 
    22         int length = (end - start) / 2;
    23 
    24         long long left = InversePairsCore(copy, data, start, start + length);
    25         long long right = InversePairsCore(copy, data, start + length + 1, end);
    26 
    27         int i = start + length;
    28         int j = end;
    29         int indexCopy = end;
    30         long long count = 0;
    31         while (i >= start && j >= start + length + 1) {
    32             if (data[i] > data[j]) {
    33                 copy[indexCopy--] = data[i--];
    34                 count += j - start - length;
    35             }
    36             else {
    37                 copy[indexCopy--] = data[j--];
    38             }
    39         }
    40 
    41         for (; i >= start; --i)
    42             copy[indexCopy--] = data[i];
    43         for (; j >= start + length + 1; --j)
    44             copy[indexCopy--] = data[j];
    45 
    46         return count + left + right;
    47     }
    48 };


  • 相关阅读:
    外键的缺陷
    laravel 关联模型
    n的阶乘末尾出现的次数
    JavaScript的self和this使用小结
    cocos2dx中的内存管理方式
    c++ 与 lua 简单交互参数介绍
    c++的单例模式及c++11对单例模式的优化
    cocos2dx帧动画
    cocos2dx中坐标系
    cocos2dx中替代goto的用法:do{}while(0)和CC_BREAK_IF
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/10959462.html
Copyright © 2020-2023  润新知