当前位置:网站首页>Sword finger offer 51. reverse pairs in the array
Sword finger offer 51. reverse pairs in the array
2022-07-27 15:56:00 【Skinny monkey 117】
Catalog
subject
Two numbers in an array , If the number in front is greater than the number in the back , Then these two numbers form a reverse order pair . Enter an array , Find the total number of reverse pairs in this array .
Time complexity : Merge sort O(nlogn)O(n \log n)O(nlogn).
Spatial complexity : Merge sort O(n)O(n)O(n), Because merge sort requires a temporary array .author :LeetCode-Solution
link :https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/shu-zu-zhong-de-ni-xu-dui-by-leetcode-solution/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .Limit :
0 <= The length of the array <= 50000
Ideas
The reverse : The elements in front of the array > The elements behind
The idea of merging and sorting can be used , Find the reverse order pair in the merging process .
merge It happens to be the previous array element > The following subarray elements are merged , Conform to the definition in reverse order .Is in the merge sort merge In the process of , Incidentally, I find the number of pairs in reverse order .
Only if both subarrays still have elements and the elements of the first subarray arr[i] > arr[j] It is possible to form a reverse order pair , And the number of reverse pairs is exactly the number of the first array from i Number of remaining elements from start to end .
merge Set in operation count Counter , Count the number of pairs in reverse order .
Answer key
/** * The finger of the sword Offer 51. Reverse pairs in arrays */ public class Offer51_reversePairs { public int reversePairs(int[] nums) { return reversePairsInternal(nums, 0, nums.length - 1); } /** * stay nums[l..r] Merge and sort on , Returns the number of sorted pairs in reverse order */ private int reversePairsInternal(int[] nums, int l, int r) { // The array is empty or has only one element if (l >= r) { return 0; } int mid = l + (r - l) / 2; // First, find the number of pairs in reverse order of the first sub array int leftCount = reversePairsInternal(nums, l, mid); // Then find the number of pairs in reverse order of the second sub array int rightCount = reversePairsInternal(nums, mid + 1, r); if (nums[mid] > nums[mid + 1]) { // After the left and right arrays are ordered , There is also a reverse order between the two arrays ,merge Process to find the number of pairs in reverse order in the consolidation process return leftCount + rightCount + merge(nums, l, mid, r); } // nums[mid] < nums[mid + 1] The whole array has been ordered , There can be no reverse order ! return leftCount + rightCount; } /** * Merge two ordered subarrays nums[l..mid] nums[mid + 1..r] Returns the number of pairs in reverse order after merging */ private int merge(int[] nums, int l, int mid, int r) { // The number of reverse order pairs generated during merging int count = 0; int aux[] = new int[r - l + 1]; for (int i = l; i <= r; i++) { aux[i - l] = nums[i]; } int i = l, j = mid + 1; for (int k = l; k <= r; k++) { if (i > mid) { // The first array has been processed , Directly splice the second array , At this time, there is no reverse order nums[k] = aux[j - l]; j++; } else if (j > r) { // The second array has been processed , Directly splice the first array , At this time, there is no reverse order nums[k] = aux[i - l]; i++; } else if (aux[i - l] <= aux[j - l]) { // Splice the first array , There is no reverse order at this time nums[k] = aux[i - l]; i++; } else { // At this point, the first array element > The second array element , // from i Start to mid All elements that end are compared to arr[j] It's all in reverse order // The number of pairs in reverse order is exactly mid - i + 1 count += mid - i + 1; nums[k] = aux[j - l]; j++; } } return count; } }
Complexity analysis
Time complexity : Merge sort O(nlogn).
Spatial complexity : Merge sort O(n), Because merge sort requires a temporary array .
边栏推荐
- Network principle (1) - overview of basic principles
- [正则表达式] 匹配开头和结尾
- 【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
- [sword finger offer] interview question 45: arrange the array into the smallest number
- 【剑指offer】面试题50:第一个只出现一次的字符——哈希表查找
- Is low code the future of development? On low code platform
- synchronized和ReentrantLock的区别
- 【剑指offer】面试题54:二叉搜索树的第k大节点
- Division of entity classes (VO, do, dto)
- Fluent -- layout principle and constraints
猜你喜欢

【剑指offer】面试题46:把数字翻译成字符串——动态规划
![[sword finger offer] interview question 42: the maximum sum of continuous subarrays -- with 0x80000000 and int_ MIN](/img/01/bbf81cccb47b6351d7265ee4a77c55.png)
[sword finger offer] interview question 42: the maximum sum of continuous subarrays -- with 0x80000000 and int_ MIN

Analysis of spark task scheduling exceptions

On juicefs

C language: minesweeping games

Fluent -- layout principle and constraints

Learn parquet file format

【剑指offer】面试题45:把数组排成最小的数

Using Lombok results in the absence of parent class attributes in the printed toString

leetcode25题:K 个一组翻转链表——链表困难题目详解
随机推荐
Causes and solutions of deadlock in threads
兆骑科创创业大赛策划承办机构,双创平台,项目落地对接
Hyperlink parsing in MD: parsing `this$ Set() `, ` $` should be preceded by a space or escape character`\`
Go language learning notes (1)
Breaking through soft and hard barriers, Xilinx releases Vitis unified software platform for developers
Stock account opening commission discount, stock trading account opening which securities company is good, is online account opening safe
Leetcode-1: sum of two numbers
【云享读书会第13期】FFmpeg 查看媒体信息和处理音视频文件的常用方法
DRF学习笔记(三):模型类序列化器ModelSerializer
【剑指offer】面试题49:丑数
Network device hard core technology insider router Chapter 22
【剑指offer】面试题53-Ⅱ:0~n-1中缺失的数字——二分查找
Modify spark to support remote access to OSS files
Using Prometheus to monitor spark tasks
The shell script reads the redis command in the text and inserts redis in batches
[tensorboard] oserror: [errno 22] invalid argument processing
[system programming] process, thread problem summary
Spark 3.0 DPP implementation logic
网络原理(1)——基础原理概述
线程间等待与唤醒机制、单例模式、阻塞队列、定时器
