当前位置:网站首页>Leetcode - Sword finger offer 51 Reverse pairs in an array
Leetcode - Sword finger offer 51 Reverse pairs in an array
2022-07-02 12:21:00 【Ostrich5yw】
The finger of the sword Offer 51. Reverse pairs in arrays
Title Description :[51]
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 .
Key points of investigation :
The first 51 topic Merge sort implementation . During sorting , Compare the size of the left and right array elements , Calculate the number of pairs in reverse order .
The first 51 topic
class Solution {
int count = 0;
public int reversePairs(int[] nums) {
mergeSort(nums, 0, nums.length - 1);
return count;
}
public void mergeSort(int[] nums, int left, int right){
if(left >= right) return;
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right);
}
public void merge(int[] nums, int left, int mid, int right){
int[] numsTemp = new int[right - left + 1];
int pointTemp = 0, pointR = mid + 1, pointL = left;
while(pointL <= mid || pointR <= right){
if(pointR > right || pointL > mid){
while(pointL <= mid){
numsTemp[pointTemp++] = nums[pointL ++];
}
while(pointR <= right){
numsTemp[pointTemp++] = nums[pointR ++];
}
break;
}
if(nums[pointL] > nums[pointR]){
count += (mid - pointL + 1);
numsTemp[pointTemp ++] = nums[pointR++];
}else{
numsTemp[pointTemp ++] = nums[pointL++];
}
}
for(int i = left;i <= right;i ++){
nums[i] = numsTemp[i - left];
}
}
}
边栏推荐
猜你喜欢

基于Arduino和ESP8266的Blink代码运行成功(包含错误分析)

Simple understanding of ThreadLocal

The blink code based on Arduino and esp8266 runs successfully (including error analysis)

arcgis js 4. Add pictures to x map

drools中then部分的写法

Embedded Software Engineer career planning

MySQL indexes and transactions

寻找二叉树中任意两个数的公共祖先

HR wonderful dividing line

From scratch, develop a web office suite (3): mouse events
随机推荐
刷题---二叉树--2
Brush questions --- binary tree --2
Input a three digit number and output its single digit, ten digit and hundred digit.
PyTorch nn.RNN 参数全解析
测试左移和右移
CDA data analysis -- common knowledge points induction of Excel data processing
Use sqoop to export ads layer data to MySQL
Leetcode209 长度最小的子数组
Simple use of drools decision table
Maximum profit of jz63 shares
Jenkins voucher management
Lekao: contents of the provisions on the responsibility of units for fire safety in the fire protection law
[I'm a mound pytorch tutorial] learning notes
Applet link generation
Leetcode14 longest public prefix
堆(优先级队列)
【C语言】十进制数转换成二进制数
kubeadm join时出现错误:[ERROR Port-10250]: Port 10250 is in use [ERROR FileAvailable--etc-kubernetes-pki
Codeforces 771 div2 B (no one FST, refers to himself)
【C语言】杨辉三角,自定义三角的行数