当前位置:网站首页>【英雄哥七月集训】第 24天: 线性树
【英雄哥七月集训】第 24天: 线性树
2022-07-25 23:54:00 【如果我是温帅帅】
一、剑指 Offer 51. 数组中的逆序对
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
leetcode剑指 offer51 java
思路
离散 nums
(query)=右边的几个数比他小
将每一个位置的 u 相加,最后得到结果
class Solution {
int n = 0, res = 0 , u = 0;
public int reversePairs(int[] nums) {
n = nums.length;
//离散化
descretize(nums);
//初始化线段树
Bit bit = new Bit(n);
//遍历每一个节点,取当前节点的 query
for(int i = n-1; i >=0 ; i--){
//System.out.printf("%d %d\n",nums[i],bit.query(nums[i]-1));
u = bit.query(nums[i]-1);
res += u;
bit.update(nums[i]);
}
return res;
}
public void descretize(int[] nums){
int[] temp = new int[n];
System.arraycopy(nums,0,temp,0,n);
Arrays.sort(temp);
for(int i = 0; i <n ; i++){
nums[i] = Arrays.binarySearch(temp,nums[i])+1;
}
}
public class Bit{
int n;
int[] tree;
public Bit(int x){
this.n = x;
this.tree = new int[x+1];
}
public int lowBit(int x){
return x&(-x);
}
public void update(int x){
while(x<=n){
tree[x]++;
x+=lowBit(x);
}
}
public int query(int x){
int ret = 0;
while(x!=0){
ret +=tree[x];
x-=lowBit(x);
}
return ret;
}
}
}
总结
边栏推荐
- 1223. Dice simulation range DP
- Demo of pointer function
- 【ManageEngine】ServiceDesk Plus荣获2022安全样板工程数据安全奖
- C# - readonly 和 const 关键字
- [intelligence question] interview intelligence question
- [JUC] concurrent keyword volatile
- Numerical learning iota, accumulate
- 赋值时'1和'b1有什么区别
- Array merge method: concat()
- Program environment and pretreatment
猜你喜欢

赋值时'1和'b1有什么区别

utility实用组件学习之swap,move,forward,exchange

C language implementation of three chess

Dead letter queue and message TTL expiration code

Docker installation redis-5.0.12 (remote access)

Get the data of Mafeng Hotel

Key and difficult points of C language pointer

arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置

Topsis与熵权法

Loading process such as reflection
随机推荐
Qpprogressbar for QT style (QSS) application
Read the field status of account in ABAP code (hidden, optional, required)
热部署和热加载有什么区别?
行为型模式之责任链模式
三板斧!助你成为优秀软件工程师
Zhiniu stock -- 09
2022-07-18 study notes of group 5 self-cultivation class (every day)
What is the difference between hot deployment and hot loading?
Array merge method: concat()
VSCode格式化Json文件
利用用户脚本优化 Yandere/Konachan 站点浏览体验
在应用中使用 Jetpack 库
LeetCode 0136. 只出现一次的数字:异或
Quick sorting of top ten sorting
A long detailed explanation of C language operators
智牛股--09
程序环境和预处理
Shardingsphere data slicing
Part 67: conversion between keypoint and point2f in opencv
疫情之下的好消息