2.1 493. Reverse Pairs (Divide and Conquer)

来源:互联网 发布:淘宝运动服童装 编辑:程序博客网 时间:2024/06/02 14:52

题目:

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

翻译:
给定一个数组NUMS,我们叫(I,J)的重要反向对,如果我<j和NUMS [I]> 2 * NUMS [J]。你需要返回给定数组中的重要反向双数。

例1:
输入:[1,3,2,3,1]
输出:2

例2:
输入:[2,4,3,5,1]
输出:3

注意:
给定数组的长度不超过50,000。
输入阵列中的所有数字是在32位整数的范围。



解题
思路:
1.复制一个数组v2并每个元素都乘二,将之排序。
2.v1从0到length 循环,每次将当前元素乘二在v2中二叉搜索得到迭代器然后将之在v2中删除,再将当前元素在v2中二叉搜索得到比其小的元素个数,最后累积返回。


代码展示:
#include<iostream>#include<vector>#include<algorithm>using namespace std;class Solution {//记录v中比aim小的元素个数并返回 int count(vector<long> &v,long aim) {int begin = 0, end = v.size() - 1, middle;if(end < 0) return 0;while(begin < end) {middle = (begin+end) /2;if(v[middle] < aim) begin = middle+1;else end = middle;}if(v[begin]>=aim) return begin;else return v.size();}//在v中查找aim 并返回迭代器 vector<long>::iterator Mysearch(vector<long>& v, long aim) {int begin = 0,end = v.size()-1;while(begin < end) {intmiddle = (begin+end)/2;if(v[middle] == aim) return v.begin()+middle;else if(v[middle] < aim) begin = middle+1;else end = middle;}return v.begin() + begin;}public:    int reversePairs(vector<int>& nums) {    int sum = 0;int n = nums.size();vector<long> v(n,0);for(int i = 0; i< n;i++) v[i] = (long)nums[i] * 2;sort(v.begin(),v.end());for(int i= 0; i< n;i++) {vector<long>::iterator iter = Mysearch(v,(long)nums[i] *2);v.erase(iter);sum += count(v,nums[i]);}return sum;    }};int main() {int arr[] = {2,4,3,5,1};vector<int> v(arr,arr+5);Solution s;cout <<s.reversePairs(v);} 

解题状态:
0 0
原创粉丝点击