493. Reverse Pairs(divide and conquer)

来源:互联网 发布:电商源码 java 编辑:程序博客网 时间:2024/06/05 15:05

1. Description

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:

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


2. Analysis

(空)


3. code

O(nlogn)

class Solution {public:    static void recursivePairs(vector<int>&nums, int start, int end, int& count) {        if(end == start ) return;         int mid = (start + end)/2;         /*一直分到最小*/        recursivePairs(nums, start, mid, count);        recursivePairs(nums, mid+1, end, count);            /*到达最小单位,(基于排序)开始计算*/        int i = start, j = mid + 1;        while( i <= mid && j <= end) {            if((long)nums[i] > (long)2*nums[j]) {                /*这一步很重要,减少时间复杂度的关键                * 借助已经排序过的单元,直接计算                */                count += (mid - i + 1);                j++;            } else {                i++;            }        }         /*已经计算过的单元划分可以进行排序*/        sort(nums.begin()+start,nums.begin()+end+1);         return;    }    int reversePairs(vector<int>& nums) {        if(nums.size() == 0 || nums.size() == 1) return 0;        int count = 0;        recursivePairs(nums,0, nums.size()-1, count);        return count;    }};

未改进的版本,Time exceed:

class Solution {public:    static void recursivePairs(vector<int>&nums, int start, int mid, int end, int& count) {        if(end == start ) return;        if(end - start == 1) {            if(nums[start] - nums[end] > nums[end])                count++;            return;        }             //关键是这里的问题,使得复杂度成了O(n^2),根据大师定理        for(int j = end; j >= mid; j--) {                for(int i = start; i < mid; i++) {                    if(nums[i] - nums[j] > nums[j])                        count++;                }        }           recursivePairs(nums, start, (start+mid-1)/2, mid-1, count);        recursivePairs(nums, mid, (mid+end)/2, end, count);       }    int reversePairs(vector<int>& nums) {        if(nums.size() == 0 || nums.size() == 1) return 0;        int count = 0;        recursivePairs(nums,0, (nums.size()-1)/2, nums.size()-1, count);        return count;    }};