2017-09-15 LeetCode_493 Reverse Pairs

来源:互联网 发布:大屏幕电子书 知乎 编辑:程序博客网 时间:2024/05/18 01:15

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.

solution:

class Solution {
2
public:
3
    void divide(vector<int>& nums, vector<int>& ans, vector<int>& d, vector<vector<int> >& temp, int start, int end) {
4
        if (start == end) return;
5
        divide(nums, ans, d, temp, start, (start+end)/2);
6
        divide(nums, ans, d, temp, (start+end)/2+1, end);
7
        int i = start, j = (start+end)/2+1, k = start;
8
        while (i <= (start+end)/2 || j <= end) {
9
            if (i == (start+end)/2+1) j++;
10
            else if (j == end+1) i++;
11
            else if ((long long)nums[i] > 2*(long long)nums[j]) {
12
                ans[i] += end-j+1;
13
                i++;
14
            } else j++;
15
        }
16
        i = start, j = (start+end)/2+1;
17
        while (i <= (start+end)/2 || j <= end) {
18
            if (i == (start+end)/2+1) {
19
                temp[0][k] = nums[j]; temp[1][k] = ans[j]; temp[2][k] = d[j];
20
                k++; j++;
21
            } else if (j == end+1) {
22
                temp[0][k] = nums[i]; temp[1][k] = ans[i]; temp[2][k] = d[i];
23
                k++; i++;
24
            } else if (nums[i] > nums[j]) {
25
                temp[0][k] = nums[i]; temp[1][k] = ans[i]; temp[2][k] = d[i];
26
                k++; i++;
27
            } else {
28
                temp[0][k] = nums[j]; temp[1][k] = ans[j]; temp[2][k] = d[j];
29
                k++; j++;
30
            }
31
        }
32
        for (int l = start; l <= end; l++) {
33
            nums[l] = temp[0][l]; ans[l] = temp[1][l]; d[l] = temp[2][l];
34
        }
35
    }
36
    int reversePairs(vector<int>& nums) {
37
        vector<int> ans, d, final, no;
38
        vector<vector<int> > temp;
39
        if (nums.size() == 0) return 0;
40
        temp.push_back(no); temp.push_back(no); temp.push_back(no);
41
        for (int i = 0; i < nums.size(); i++) {
42
            ans.push_back(0); d.push_back(i); final.push_back(0);
43
            temp[0].push_back(0); temp[1].push_back(0); temp[2].push_back(0);
44
        }
45
        divide(nums, ans, d, temp, 0, nums.size()-1);
46
        int myans = 0; 
47
        for (int i = 0; i < nums.size(); i++) {
48
            final[d[i]] = ans[i]; myans += ans[i];
49
        }
50
        return myans;
51
    }
52
};





原创粉丝点击