您的位置:首页 > 大数据 > 人工智能

leetcode 493. Reverse Pairs 归并排序统计逆序对数量 + 这个我估计是做不出来的,还是直接暴力吧

2017-12-14 09:44 686 查看
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.

题意很简单,但是AC的方法不会,我觉得循环遍历也不错,虽然肯定会超时

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <cmath>

using namespace std;

class Solution
{
public:
int reversePairs(vector<int>& nums)
{
int res = sort_and_count(nums.begin(), nums.end());
return res;
}
int sort_and_count(vector<int>::iterator begin, vector<int>::iterator end)
{
if (end - begin <= 1)
return 0;
else
{
auto mid = begin + (end - begin) / 2;
int count = sort_and_count(begin, mid) + sort_and_count(mid, end);
for (auto i = begin, j = mid; i != mid; ++i)
{
while (j != end && (*i) > 2L * (*j) )
++j;
count += j - mid;
}
inplace_merge(begin, mid, end);
return count;
}
}

int reversePairsByLoop(vector<int>& nums)
{
int count = 0;
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
long long a = nums[i];
long long b = ((long long)nums[j]) << 1;
if (a > b)
count++;
}
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: