zoukankan      html  css  js  c++  java
  • 面试题36 数组中的逆序对

    题目描述

    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
     1 class Solution {
     2 public:
     3     int InversePairsCore(vector<int> &data,vector<int>&copy,int start,int end)
     4     {
     5         if(start==end)
     6         {
     7             copy[start]=data[start];
     8             return 0;
     9         }
    10         int length = (end-start)/2;
    11         int left = InversePairsCore(copy,data,start,start+length);
    12         int right = InversePairsCore(copy,data,start+length+1,end);
    13           
    14         int i = start + length;
    15         int j = end;
    16         int indexCopy = end;
    17         int count=0;
    18         while(i>=start&&j>=start+length+1)
    19         {
    20             if(data[i]>data[j])
    21             {
    22                 copy[indexCopy--]=data[i--];
    23                 count+=j-start-length;
    24             }
    25             
    26             else
    27             {
    28                 copy[indexCopy--]=data[j--];
    29             }
    30         }
    31         for(;i>=start;--i)
    32             copy[indexCopy--] = data[i];
    33         for(;j>=start+length+1;--j)
    34             copy[indexCopy--] = data[j];
    35         return left+right+count;
    36         }
    37     int InversePairs(vector<int> data) {
    38         int length = data.size();
    39         if(length<=0)
    40             return 0;
    41         vector<int> copy;
    42         for(int i=0;i<length;i++)
    43             copy.push_back(data[i]);
    44         int count = InversePairsCore(data,copy,0,length-1);
    45         copy.clear();
    46         return count;
    47     }
    48      
    49      
    50 };
  • 相关阅读:
    调试IPV6
    [super class]和[self class]
    Django2 + python3 上传图片
    django2 + python3 显示静态文件中的图片
    机器工厂——贪心
    Handstand 2——AT(先打表)
    Low Elements--AT
    Double Factorial——AT
    Brick Break——AT
    变音量——动态规划
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5358600.html
Copyright © 2011-2022 走看看