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的方法不会,我觉得循环遍历也不错,虽然肯定会超时
代码如下:
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; } };
相关文章推荐
- mysql并统计同一字段的数量,最后按这个数量降序排序
- 数据结构:归并排序 && 逆序对统计
- jxl.jar 的百度百科,根据这个还是可以搞出来的,不过就是修改那块写的不是很好,修改其实可以直接读取数据并操作。
- hdu 1394 求循环串的最小逆序数 暴力法 线段树 归并排序3种方法
- hihocoder #1141 : 二分·归并排序之逆序对
- 数据结构--归并排序的应用(求逆序数 蓝桥杯--小朋友排队)
- poj-2299-逆序数-归并排序
- 数据结构实验之排序五:归并求逆序数
- 平时,需要查看电脑运行情况报告,就用这个工具查看统计出来
- [leetcode] Merge Sorted Array 直接插入排序法解题
- HDU ~ 1394 ~ Minimum Inversion Number(暴力||归并排序||线段树||树状数组)
- leetcode+DP,这个DP方程我想出来了
- 利用归并排序思想求数组中的逆序对
- 【hiho39】二分·归并排序之逆序对
- c语言实现直接插入排序(正序和逆序)
- pat乙级1030这个思想真的不错 比我直接暴力两层循环好多
- 估计创建索引需要的排序空间数量
- 字符串练习(1.统计字符串中字串的数量2.字符串逆序3.字符串替换)
- 从逆序对问题展开 归并排序习题归纳
- 统计序列中当前元素之前比它大的元素个数(两种解法:归并排序应用,线段树)