• 剑指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 };
  • 相关阅读:
    LeetCode-Palindrome Partitioning II
    LeetCode-Palindrome Partitioning
    LeetCode-Permutation Sequence
    LeetCode-Anagrams
    LeetCode-Text Justification
    LeetCode-Best Time to Buy and Sell Stock III
    LeetCode-Best Time to Buy and Sell Stock II
    LeetCode-Best Time to Buy and Sell Stock
    LeetCode-N-Queens II
    BZOJ 5390: [Lydsy1806月赛]糖果商店
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6943440.html
Copyright © 2020-2023  润新知