Hard-题目11:315. Count of Smaller Numbers After Self

树状数组解决右侧行问题
本文介绍了一种利用树状数组(Binary Indexed Tree)高效解决特定数组问题的方法。通过实例详细解析了如何构建和应用树状数组来计算每个元素右侧较小元素的数量,并附带了Java实现代码。

题目原文:
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
题目大意:
给出一个数组,计算每个元素右边有几个比它小的元素,组成一个新的数组返回。
题目分析:
这里需要用到一种高级数据结构叫做“树状数组”,又叫Binary Indexed Tree或Fenwick tree,其特点是查询和修改节点都是O(logn)的,用于快速求数组的前n项和。
构建方法:
设原数组是a[1…n],按如图方式构造数组c:(from 百度百科)
这里写图片描述
C[1]=a[1],c[2]=a[1]+a[2],….c[8]=a[1]+…+a[8],
树状数组有两个api,这两个api的时间复杂度都是O(logn)的,n为数组长度,具体实现略,有兴趣可以自行百度。

void add(int* tree,int k,int num) // 在a[k]上增加num,更新树状数组tree
int get(int* tree,int k) // 求a[1]+…+a[k]的和

再回到这道题,先求最小值和最大值,记为min和max,然后平移区间使得min=1,(若min不为1,则整个数组都减去min和1的差值)然后基于数组num(其中最小值修正为1,对应最大值为max-min+1) 构建树状数组tree[1…max-min+1],其中对应的a数组的a[i]代表num数组中i出现的次数。
接下来逆向扫描num数组,每扫到一个元素num[i],调用get函数求树状数组中a[1]到a[num[i]-1]的和,这个和值就是num数组中i右边比num[i]小的个数!!(这里最难理解,稍后说明),再调用add函数把num[i]加到a中。
时间复杂度:扫描一遍数组O(n),每个元素调用了两个O(logk)复杂度的api,其中k为树状数组长度,总复杂度为O(nlog(max-min)).
上面说了这么多有点抽象,下面举个栗子~~(看明白的童鞋或者嫌我墨迹的童鞋略过吧)
输入数组:[5,6,-1,1] (答案为:[2,2,0,0])
首先修正数组使得最小值为1(否则会出现数组越界):
nums[]=[6,8,1,3],min=1,max=8
然后构建tree[1..8](因为tree的值很难写,就写图中下方的a数组)
逆向扫描数组:此时a数组初始化为全0
nums[i]=3,调用get函数求a[1]+a[2]为0(即1,2这两个数还没出现过),调用add函数使得a[3]++,
此时a数组:[0,0,1,0,0,0,0,0]
Nums[i]=1,调用get函数返回0(因为1左边没有数据了),调用add函数使得a[1]++.
此时a数组:[1,0,1,0,0,0,0,0]
Nums[i]=8,调用get函数求a[1]+…+a[7]=2,调用add函数使得a[8]++
此时a数组:[1,0,1,0,0,0,0,1]
Nums[i]=6,调用get函数求a[1]+…+a[5]=2,调用add函数使得a[6]++.
此时a数组:[1,0,1,0,0,1,0,1]
从下往上读取get的返回值,得到数组[2,2,0,0]即为答案。
源码:(language:java)

public class Solution {
    public List<Integer> countSmaller(int[] nums) {
        LinkedList<Integer> res = new LinkedList<Integer>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        // find min value and minus min by each elements, plus 1 to avoid 0 element
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            min = (nums[i] < min) ? nums[i]:min;
        }
        int[] nums2 = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            nums2[i] = nums[i] - min + 1;
            max = Math.max(nums2[i],max);
        }
        int[] tree = new int[max+1];
        for (int i = nums2.length-1; i >= 0; i--) {
            res.addFirst(get(nums2[i]-1,tree));
            update(nums2[i],tree);
        }
        return res;
    }
    private int get(int i, int[] tree) {
        int num = 0;
        while (i > 0) {
            num +=tree[i];
            i -= i&(-i);
        }
        return num;
    }
    private void update(int i, int[] tree) {
        while (i < tree.length) {
            tree[i] ++;
            i += i & (-i);
        }
    }
}

成绩:
8ms,beats 97.33%,众数11ms,8.79%
Cmershen的碎碎念:
返回类型是List,因为要从下往上读get函数的返回值,故使用链表的实现类LinkedList,因为提供了addFirst()方法.

内容概要:本文介绍了一个基于Matlab的综合能源系统优化调度仿真资源,重点实现了含光热电站、有机朗肯循环(ORC)和电含光热电站、有机有机朗肯循环、P2G的综合能源优化调度(Matlab代码实现)转气(P2G)技术的冷、热、电多能互补系统的优化调度模型。该模型充分考虑多种能源形式的协同转换与利用,通过Matlab代码构建系统架构、设定约束条件并求解优化目标,旨在提升综合能源系统的运行效率与经济性,同时兼顾灵活性供需不确定性下的储能优化配置问题。文中还提到了相关仿真技术支持,如YALMIP工具包的应用,适用于复杂能源系统的建模与求解。; 适合人群:具备一定Matlab编程基础和能源系统背景知识的科研人员、研究生及工程技术人员,尤其适合从事综合能源系统、可再生能源利用、电力系统优化等方向的研究者。; 使用场景及目标:①研究含光热、ORC和P2G的多能系统协调调度机制;②开展考虑不确定性的储能优化配置与经济调度仿真;③学习Matlab在能源系统优化中的建模与求解方法,复现高水平论文(如EI期刊)中的算法案例。; 阅读建议:建议读者结合文档提供的网盘资源,下载完整代码和案例文件,按照目录顺序逐步学习,重点关注模型构建逻辑、约束设置与求解器调用方式,并通过修改参数进行仿真实验,加深对综合能源系统优化调度的理解。
codecHandlesFormat: no format, so no extra checks 2025-10-31 10:14:07.929 5301-5301 MediaCodecList com.tencent.yolov5ncnn D codecHandlesFormat: no format, so no extra checks 2025-10-31 10:14:07.938 5301-5349 CCodec com.tencent.yolov5ncnn D allocate(c2.goldfish.h264.decoder) 2025-10-31 10:14:07.942 5301-5349 ApexCodecsLazy com.tencent.yolov5ncnn I Failed to load libcom.android.media.swcodec.apexcodecs.so: dlopen failed: library "libcom.android.media.swcodec.apexcodecs.so" not found 2025-10-31 10:14:07.943 5301-5349 Codec2Client com.tencent.yolov5ncnn I Available Codec2 services: "default" "software" 2025-10-31 10:14:07.945 5301-5349 CCodec com.tencent.yolov5ncnn I setting up 'default' as default (vendor) store 2025-10-31 10:14:07.959 5301-5349 CCodec com.tencent.yolov5ncnn I Created component [c2.goldfish.h264.decoder] for [c2.goldfish.h264.decoder] 2025-10-31 10:14:07.965 5301-5349 CCodecConfig com.tencent.yolov5ncnn D read media type: video/avc 2025-10-31 10:14:07.972 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: algo.buffers.max-count.values 2025-10-31 10:14:07.975 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: output.subscribed-indices.values 2025-10-31 10:14:07.975 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: input.buffers.allocator-ids.values 2025-10-31 10:14:07.975 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: output.buffers.allocator-ids.values 2025-10-31 10:14:07.981 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: algo.buffers.allocator-ids.values 2025-10-31 10:14:07.981 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: output.buffers.pool-ids.values 2025-10-31 10:14:07.982 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D extent() != 1 for single value type: algo.buffers.pool-ids.values 2025-10-31 10:14:07.984 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D ignored struct field coded.color-format.locations 2025-10-31 10:14:07.986 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D ignored struct field resources.needed.values 2025-10-31 10:14:07.987 5301-5349 CCodecConfig com.tencent.yolov5ncnn D ignoring local param raw.size (0xd2001800) as it is already supported 2025-10-31 10:14:07.987 5301-5349 CCodecConfig com.tencent.yolov5ncnn D ignoring local param default.color (0x5200180b) as it is already supported 2025-10-31 10:14:07.987 5301-5349 ReflectedParamUpdater com.tencent.yolov5ncnn D ignored struct field raw.hdr-static-info.mastering 2025-10-31 10:14:07.992 5301-5349 CCodecConfig com.tencent.yolov5ncnn I query failed after returning 12 values (BAD_INDEX) 2025-10-31 10:14:07.993 5301-5349 CCodecConfig com.tencent.yolov5ncnn D c2 config diff is Dict { c2::u32 coded.pl.level = 20496 c2::u32 coded.pl.profile = 20481 c2::u32 coded.vui.color.matrix = 0 c2::u32 coded.vui.color.primaries = 0 c2::u32 coded.vui.color.range = 2 c2::u32 coded.vui.color.transfer = 0 c2::u32 default.color.matrix = 0 c2::u32 default.color.primaries = 0 c2::u32 default.color.range = 0 c2::u32 default.color.transfer = 0 c2::u32 input.buffers.max-size.value = 6291456 c2::u32 input.delay.value = 0 string input.media-type.value = "video/avc" c2::u32 output.delay.value = 8 string output.media-type.value = "video/raw" c2::u32 raw.color.matrix = 0 c2::u32 raw.color.primaries = 0 c2::u32 raw.color.range = 2 c2::u32 raw.color.transfer = 0 c2::u32 raw.max-size.height = 240 c2::u32 raw.max-size.width = 320 c2::u32 raw.pixel-format.value = 35 c2::i32 raw.rotation.flip = 0 c2::i32 raw.rotation.value = 0 c2::u32 raw.sar.height = 1 c2::u32 raw.sar.width = 1 c2::u32 raw.size.height = 240 c2::u32 raw.size.width = 320 c2: 2025-10-31 10:14:07.993 5301-5349 ColorUtils com.tencent.yolov5ncnn W expected specified color aspects (2:0:0:0) 2025-10-31 10:14:08.013 5301-5301 MediaCodec com.tencent.yolov5ncnn E Media Quality Service not found. 2025-10-31 10:14:08.016 5301-5348 SurfaceUtils com.tencent.yolov5ncnn D connecting to surface 0x7fb26d4de740, reason connectToSurface 2025-10-31 10:14:08.016 5301-5348 MediaCodec com.tencent.yolov5ncnn I [c2.goldfish.h264.decoder] setting surface generation to 5428225 2025-10-31 10:14:08.016 5301-5348 SurfaceUtils com.tencent.yolov5ncnn D disconnecting from surface 0x7fb26d4de740, reason connectToSurface(reconnect) 2025-10-31 10:14:08.017 5301-5348 SurfaceUtils com.tencent.yolov5ncnn D connecting to surface 0x7fb26d4de730, reason connectToSurface(reconnect-with-listener) 2025-10-31 10:14:08.021 5301-5349 CCodecBufferChannel com.tencent.yolov5ncnn I Using latch times for frame rendered signals - present fences not supported 2025-10-31 10:14:08.021 5301-5349 CCodec com.tencent.yolov5ncnn D [c2.goldfish.h264.decoder] buffers are bound to CCodec for this session 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for color-format 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for track-id 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for frame-count 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for language 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for display-width 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for csd-1 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for durationUs 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for display-height 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for native-window 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for native-window-generation 2025-10-31 10:14:08.022 5301-5349 CCodecConfig com.tencent.yolov5ncnn D no c2 equivalents for flags 2025-10-31 10:14:08.026 5301-5349 CCodecConfig com.tencent.yolov5ncnn D c2 config diff is c2::u32 coded.pl.level = 20494 c2::u32 coded.pl.profile = 20484 c2::u32 raw.size.height = 1296 c2::u32 raw.size.width = 2304 2025-10-31 10:14:08.032 5301-5349 Codec2Client com.tencent.yolov5ncnn W query -- param skipped: index = 1107298332. 2025-10-31 10:14:08.032 5301-5349 CCodec com.tencent.yolov5ncnn D client requested max input size 574215, which is smaller than what component recommended (6291456); overriding with component recommendation. 2025-10-31 10:14:08.032 5301-5349 CCodec com.tencent.yolov5ncnn W This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range. 2025-10-31 10:14:08.032 5301-5349 CCodec com.tencent.yolov5ncnn D encoding statistics level = 0 2025-10-31 10:14:08.032 5301-5349 CCodec com.tencent.yolov5ncnn D setup formats input: AMessage(what = 0x00000000) = { int32_t height = 1296 int32_t level = 16384 int32_t max-input-size = 6291456 string mime = "video/avc" int32_t profile = 8 int32_t width = 2304 Rect crop(0, 0, 2303, 1295) } 2025-10-31 10:14:08.032 5301-5349 CCodec com.tencent.yolov5ncnn D setup formats output: AMessage(what = 0x00000000) = { int32_t android._color-format = 2135033992 int32_t android._video-scaling = 1 int32_t rotation-degrees = 0 int32_t color-standard = 1 int32_t color-range = 2 int32_t color-transfer = 3 int32_t sar-height = 1 int32_t sar-width = 1 Rect crop(0, 0, 2303, 1295) int32_t width = 2304 int32_t height = 1296 int32_t max-height = 240 int32_t max-width = 320 string mime = "video/raw" int32_t android._dataspace = 260 int32_t color-format = 2135033992 } 2025-10-31 10:14:08.033 5301-5349 CCodecConfig com.tencent.yolov5ncnn I query failed after returning 12 values (BAD_INDEX) 2025-10-31 10:14:08.033 5301-5349 CCodecConfig com.tencent.yolov5ncnn D c2 config diff is c2::u32 raw.max-size.height = 1296 c2::u32 raw.max-size.width = 2304 2025-10-31 10:14:08.041 5301-5349 Codec2Client com.tencent.yolov5ncnn W query -- param skipped: index = 1342179345. 2025-10-31 10:14:08.042 5301-5349 Codec2Client com.tencent.yolov5ncnn W query -- param skipped: index = 2415921170. 2025-10-31 10:14:08.042 5301-5349 Codec2Client com.tencent.yolov5ncnn W query -- param skipped: index = 1610614798. 2025-10-31 10:14:08.042 5301-5349 Codec2Client com.tencent.yolov5ncnn W query -- param skipped: index = 2684356609. 2025-10-31 10:14:08.043 5301-5349 C2Store com.tencent.yolov5ncnn D Using DMABUF Heaps 2025-10-31 10:14:08.047 5301-5349 CCodecBufferChannel com.tencent.yolov5ncnn D [c2.goldfish.h264.decoder#393] Created input block pool with allocatorID 16 => poolID 17 - OK (0) 2025-10-31 10:14:08.048 5301-5349 CCodecBufferChannel com.tencent.yolov5ncnn D [c2.goldfish.h264.decoder#393] Query output surface allocator returned 0 params => BAD_INDEX (6) 2025-10-31 10:14:08.050 5301-5349 CCodecBufferChannel com.tencent.yolov5ncnn I [c2.goldfish.h264.decoder#393] Created output block pool with allocatorID 18 => poolID 25 - OK 2025-10-31 10:14:08.051 5301-5349 CCodecBufferChannel com.tencent.yolov5ncnn D [c2.goldfish.h264.decoder#393] Configured output block pool ids 25 => OK 2025-10-31 10:14:08.052 5301-5349 Codec2-Out...ufferQueue com.tencent.yolov5ncnn D remote graphic buffer migration 0/0 2025-10-31 10:14:08.052 5301-5349 Codec2Client com.tencent.yolov5ncnn D setOutputSurface -- failed to set consumer usage (6/BAD_INDEX) 2025-10-31 10:14:08.052 5301-5349 Codec2Client com.tencent.yolov5ncnn D setOutputSurface -- generation=5428225 consumer usage=0x900 2025-10-31 10:14:08.059 5301-5349 Codec2Client com.tencent.yolov5ncnn D Surface configure completed 2025-10-31 10:14:08.060 5301-5349 DMABUFHEAPS com.tencent.yolov5ncnn I Using DMA-BUF heap named: system 2025-10-31 10:14:08.264 5301-5349 CCodecConfig com.tencent.yolov5ncnn D c2 config diff is c2::u32 raw.crop.height = 1296 c2::u32 raw.crop.left = 0 c2::u32 raw.crop.top = 0 c2::u32 raw.crop.width = 2304 2025-10-31 10:14:08.270 5301-5301 System.out com.tencent.yolov5ncnn I image == null!!!!!!!!!!! 2025-10-31 10:14:08.270 5301-5301 System.out com.tencent.yolov5ncnn I surfaceChanged!!!!!!!!!!!!!!! 2025-10-31 10:14:08.972 5301-5301 Choreographer com.tencent.yolov5ncnn I Skipped 41 frames! The application may be doing too much work on its main thread. 2025-10-31 10:14:08.979 5301-5325 HWUI com.tencent.yolov5ncnn I Davey! duration=954ms; Flags=1, FrameTimelineVsyncId=53495, IntendedVsync=2809136577648, Vsync=2809136577648, InputEventId=0, HandleInputStart=2809138486400, AnimationStart=2809138526700, PerformTraversalsStart=2809138583400, DrawStart=2809632751300, FrameDeadline=2809153244314, FrameStartTime=2809138462300, FrameInterval=16666666, WorkloadTarget=16666666, SyncQueued=2809633289100, SyncStart=2809838331200, IssueDrawCommandsStart=2809838546200, SwapBuffers=2809840024200, FrameCompleted=2810296163000, DequeueBufferDuration=454788300, QueueBufferDuration=351100, GpuCompleted=2810054319600, SwapBuffersCompleted=2810296163000, DisplayPresentTime=0, CommandSubmissionCompleted=2809840024200, 2025-10-31 10:14:09.027 5301-5301 InsetsController com.tencent.yolov5ncnn D hide(ime(), fromIme=false) 2025-10-31 10:14:09.027 5301-5301 ImeTracker com.tencent.yolov5ncnn I com.tencent.yolov5ncnn:87efbc8a: onCancelled at PHASE_CLIENT_ALREADY_HIDDEN 2025-10-31 10:14:13.051 5301-5352 BufferPoolAccessor2.0 com.tencent.yolov5ncnn D bufferpool2 0x7fb23d4b7b78 : 6(37748736 size) total buffers - 4(25165824 size) used buffers - 0/6 (recycle/alloc) - 6/6 (fetch/transfer) 2025-10-31 10:14:13.051 5301-5352 BufferPoolAccessor2.0 com.tencent.yolov5ncnn D evictor expired: 1, evicted: 1
11-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值