美文网首页
数组中的逆序对

数组中的逆序对

作者: 吃掉夏天的怪物 | 来源:发表于2021-05-03 13:06 被阅读0次

    剑指 Offer 51. 数组中的逆序对

    难度困难403
    在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
    示例 1:
    输入: [7,5,6,4]
    输出: 5</pre>
    限制:
    0 <= 数组长度 <= 50000

    class Solution {
    public:
        int Core(vector<int>&nums, vector<int>&copy, int start, int end){
            if(start == end){
                copy[start] = nums[start];
                return 0;
            }
            int half = (end-start)/2;
            int left = Core(copy,nums,start,start+half);
            int right = Core(copy,nums,start+half+1,end);
            int i = start + half;
            int j = end;
            int idxC = end;
            int count = 0;
            while(i>=start && j>=start+half+1){
                if(nums[i] > nums[j]){
                    copy[idxC--] = nums[i--];
                    count += j-start-half;
                }else{
                    copy[idxC--] = nums[j--];
                }
            }
             for(;i>=start;--i){
                copy[idxC--] = nums[i];
            }
            for(;j>=start+half+1;--j) {
                copy[idxC--] = nums[j];
            }
            return left+right+count;
    
        }
    
        int reversePairs(vector<int>& nums) {
           int n = nums.size();
           if(n <= 0) return 0;
           int i =0;
           vector<int> copy(n);
           for(auto it:nums){
               copy[i++] = it;
           }
           
           return Core(nums,copy,0,n-1);
    
        }
    };
    

    相关文章

      网友评论

          本文标题:数组中的逆序对

          本文链接:https://www.haomeiwen.com/subject/jhsnrltx.html