zoukankan      html  css  js  c++  java
  • 剑指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 };


  • 相关阅读:
    WEB环境搭建(tomcat)、Eclipse连接tomcat
    spring—springmvc整合
    声明式事务
    mybatis—当表的字段名和实体类的列名不对应时的三种处理方式
    Spring整合MyBatis
    mybatis关系映射(1对1,1对多,多对多)
    mybatis
    编程式事务
    使用maven在netbeans下构建wicket项目
    mysql问题Connection using old (pre-4.1.1) authentication protocol refused (client option 'secure_auth' enabled)的解决方法
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/10959462.html
Copyright © 2011-2022 走看看