leetcode 493. Reverse Pairs

  一道归并排序求逆序对的变体题。需要注意的是输入数据乘以2后可能超出int范围。

  AC代码如下:

 1 class Solution {
 2     vector<int> merge(vector<int> a1, vector<int> a2, int& sum)
 3     {
 4         vector<int> merged;
 5         int p1 = 0, p2 = 0;
 6         for (int i = 0,j=0; i<a1.size(); ++i)
 7         {
 8             for(;j<a2.size()&&(long long)a1[i]>2*(long long)a2[j];j++);
 9             sum+=j;
10         }
11         while (p1 != a1.size() && p2 != a2.size())
12         {
13             if (a1[p1]>a2[p2])
14             {
15                 merged.push_back(a2[p2]);
16                 p2++;
17             }
18             else
19             {
20                 merged.push_back(a1[p1]);
21                 p1++;
22             }
23         }
24         while (p1 != a1.size())
25         {
26             merged.push_back(a1[p1]);
27             p1++;
28         }
29         while (p2 != a2.size())
30         {
31             merged.push_back(a2[p2]);
32             p2++;
33         }
34         return merged;
35     }
36 
37     int mergeSort(vector<int>& nums, int l, int r)
38     {
39         int sum = 0;
40         if (l + 1 >= r)
41         {
42             return 0;
43         }
44         else
45         {
46             int m = (l + r) / 2;
47             sum += mergeSort(nums, l, m);
48             sum += mergeSort(nums, m, r);
49             vector<int> vl, vr, merged;
50             for (int i = l; i<m; ++i)
51             {
52                 vl.push_back(nums[i]);
53             }
54             for (int i = m; i<r; ++i)
55             {
56                 vr.push_back(nums[i]);
57             }
58             merged = merge(vl, vr, sum);
59             for (int i = 0; i<merged.size(); ++i)
60             {
61                 nums[i + l] = merged[i];
62             }
63             return sum;
64         }
65     }
66 
67 public:
68     int reversePairs(vector<int>& nums) {
69         return mergeSort(nums, 0, nums.size());
70     }
71 };
View Code

  leetcode是个练白板编程的好地方(

posted @ 2017-11-17 14:31  Al_X  阅读(244)  评论(0编辑  收藏  举报