Lintcode248 Count of Smaller Number solution 题解

【题目描述】

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/

转载于:https://my.oschina.net/u/3776581/blog/1620285

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值