首页 技术 正文
技术 2022年11月17日
0 收藏 898 点赞 3,719 浏览 880 个字

【题目描述】

Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) and an query list. For each query, give you an integer, return the number of element in the array that are smaller than the given integer.

Notice:We suggest you finish problem Segment Tree Build and Segment Tree Query II  first.

给定一个整数数组 (下标由 0 到 n-1,其中 n 表示数组的规模,数值范围由 0 到 10000),以及一个 查询列表。对于每一个查询,将会给你一个整数,请你返回该数组中小于给定整数的元素的数量。

【注】在做此题前,最好先完成线段树的构造线段树查询 II这两道题目。

【题目链接】

www.lintcode.com/en/problem/count-of-smaller-number/

【题目解析】

此题可以用排序+二分查找的方法来做。先对数组排序,然后对于每个查询,用二分查找在数组中进行查询,找到原数组中第一个比查询数大的数,然后再从后往前统计。

由于这道题目不是查找==而是选择第一个>(num)的数的位置,所以while语句里面可以把>和=归为同一个分支>=,因为(==)存在包含重复数(duplicate)的情况,所以要和>一样,end指针前移替换mid。

那么另一个分支<,除了将start后移,还要更新返回值res。

第二点,如果while循环的约束条件是start < end,假如循环到最后start = end – 1,并且num就在end呢?这时应该返回res = start + 1,推测前一步,start = end – 2的时候,end的前移只能到mid为止,不能是mid – 1,否则就跳过了可能为所求结果的mid。

【参考答案】

www.jiuzhang.com/solutions/count-of-smaller-number/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905