【leetcode】【hard】493. Reverse Pairs​​​​​​​

本文详细解析了LeetCode上的493题——逆序对问题,介绍了如何使用归并排序的思想来高效地解决这一问题。通过将数组不断划分成小的区间,并利用归并过程中的有序特性,快速找到所有逆序对,最终返回逆序对的数量。

493. Reverse Pairs

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

You need to return the number of important reverse pairs in the given array.

Example1:

Input: [1,3,2,3,1]
Output: 2

Example2:

Input: [2,4,3,5,1]
Output: 3

Note:

  1. The length of the given array will not exceed 50,000.
  2. All the numbers in the input array are in the range of 32-bit integer.

题目链接:https://leetcode-cn.com/problems/reverse-pairs/

 

思路

用归并排序的思路,不断向下划分到小区间,因为merge的2段都是有序的,因此找逆序快,每次merge只看当前的逆序数量,向上再不断累加。

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        int len = nums.size();
        if(len<=1) return 0;
        vector<int> tmp(len);
        return sort(nums, tmp, 0, len-1);
    }
    int sort(vector<int> &nums, vector<int> &temp, int l, int r){
        if(l>=r) return 0;
        int mid = l + (r-l)/2;
        int sum =  sort(nums, temp, l, mid) + sort(nums, temp, mid+1, r);

        //merge 
        int l1 = l, l2 = mid+1;
        while(l1<=mid && l2<=r){
            if((long)nums[l1] > (long)nums[l2]*2){
                sum += (mid-l1+1);
                ++l2;
            }else{
                ++l1;
            }
        }

        //sort
        int idx=0;
        l1 = l;
        l2 = mid+1;
        while(l1<=mid && l2<=r){
            if(nums[l1]<=nums[l2]){
                temp[idx++] = nums[l1++];
            }else{
                temp[idx++] = nums[l2++];
            }
        }
        while(l1<=mid){
            temp[idx++] = nums[l1++];
        }
        while(l2<=r){
            temp[idx++] = nums[l2++];
        }
        for(int i=l; i<=r; ++i){
            nums[i] = temp[i-l];
        }

        return sum;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值