zoukankan      html  css  js  c++  java
  • 剑指offer之【数组中的逆序对】

    题目:

      数组中的逆序对

    链接:

      https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

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

    思路:

      受归并排序算法的启发,比较前后两段数组的大小,并计算逆序数;

    代码:

      

     1 class Solution {
     2 public:
     3     int InversePairs(vector<int> data){
     4         int len = data.size();
     5         res =0;
     6         if(len <= 0)
     7               return 0;
     8         vector<int> da = data;
     9         MergeSort(data,da,0,len-1);
    10         res = res%1000000007;
    11         return res;
    12     }
    13     void MergeSort(vector<int> &data,vector<int> &data1, int l , int h){
    14         int mid;
    15         if(l == h){
    16             data1[l] = data[l];
    17         }
    18         else{
    19             mid = (l+h)/2;
    20             MergeSort(data1,data,l,mid);
    21             MergeSort(data1,data,mid+1,h);
    22             Merge(data,data1,l,mid,h);
    23         }
    24     }
    25     void Merge(vector<int> &data,vector<int> &data1, int l, int m, int h){
    26         int i,j,k;
    27         for(i = l,j= m+1;i <= m && j<= h; ++l){
    28             if(data[i] < data[j]){
    29                 data1[l] = data[i++];
    30             }
    31             else{
    32                 data1[l] = data[j++];
    33                 res += (m-i+1);
    34                 res = res%1000000007;
    35             }
    36         }
    37         if(i<=m){
    38             for(k=0;k<=m-i;++k){
    39                 data1[l+k] = data[i+k];
    40             }
    41         }
    42         if(j <= h){
    43             for(k=0;k<= h-j;++k){
    44                 data1[l+k] = data[j+k];
    45             }
    46         }
    47     }
    48 private:
    49     int res;
    50 };
  • 相关阅读:
    theano 深度学习大全
    theano 深度学习大全
    hann function
    hann function
    matlab 各种文件的读取(及读写问题的解决)
    matlab 各种文件的读取(及读写问题的解决)
    极简代码(八)—— binary activation function
    极简代码(八)—— binary activation function
    微积分基本概念相关证明
    微积分基本概念相关证明
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6943440.html
Copyright © 2011-2022 走看看