当前位置:网站首页>LeetCode—剑指 Offer 51. 数组中的逆序对
LeetCode—剑指 Offer 51. 数组中的逆序对
2022-07-02 09:43:00 【Ostrich5yw】
剑指 Offer 51. 数组中的逆序对
题目描述:[51]
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
考察重点:
第51题归并排序实现。在排序过程中,比较左右两数组元素大小时,计算逆序对个数。
第51题
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];
}
}
}
边栏推荐
- Leetcode209 subarray with the smallest length
- Leetcode topic [array] -540- single element in an ordered array
- 自然语言处理系列(三)——LSTM
- SCM power supply
- CDA data analysis -- Introduction and use of aarrr growth model
- 排序---
- 【工控老马】西门子PLC Siemens PLC TCP协议详解
- drools中then部分的写法
- Codeforces 771 div2 B (no one FST, refers to himself)
- 机械臂速成小指南(七):机械臂位姿的描述方法
猜你喜欢

BEAUTIFUL GGPLOT VENN DIAGRAM WITH R

From scratch, develop a web office suite (3): mouse events

PyTorch搭建LSTM实现服装分类(FashionMNIST)

小程序链接生成

Larvel modify table fields

HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R

xss-labs-master靶场环境搭建与1-6关解题思路

conda常用命令汇总

排序---

Differences between nodes and sharding in ES cluster
随机推荐
Take you ten days to easily finish the finale of go micro services (distributed transactions)
Go学习笔记—基于Go的进程间通信
(C语言)输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
Yygh-9-make an appointment to place an order
From scratch, develop a web office suite (3): mouse events
Leetcode14 最长公共前缀
Leetcode922 按奇偶排序数组 II
Mish-撼动深度学习ReLU激活函数的新继任者
Log4j2
HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
Repeat, tile and repeat in pytorch_ The difference between interleave
Depth filter of SvO2 series
计算二叉树的最大路径和
Natural language processing series (I) -- RNN Foundation
SparkContext: Error initializing SparkContext解决方法
Deep understanding of P-R curve, ROC and AUC
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
drools执行String规则或执行某个规则文件
二分刷题记录(洛谷题单)区间的甄别
输入一个三位的数字,输出它的个位数,十位数、百位数。