Lintcode : 统计比给定整数小的数的个数

统计比给定整数小的数的个数

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

您在真实的面试中是否遇到过这个题? 
Yes
样例

对于数组 [1,2,7,8,5] ,查询 [1,8,5],返回 [0,4,2]

注意

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

挑战

可否用一下三种方法完成以上题目。

  1. 仅用循环方法

  2. 分类搜索 和 二进制搜索

  3. 构建 线段树 和 搜索

标签   Expand  

相关题目   Expand  

Timer   Expand 
解题思路:
直接使用2分搜索即可

public class Solution {
   /**
     * @param A: An integer array
     * @return: The number of element in the array that
     *          are smaller that the given integer
     */
    public ArrayList<Integer> countOfSmallerNumber(int[] A, int[] queries) {
        // write your code here
       Arrays.sort(A);
        ArrayList<Integer> res = new ArrayList<>();
        for(int x:queries){
            int tmp =  lower_bound(x, 0, A.length-1, A);
             res.add(tmp);
        }
        return res;
   }
  
   public int lower_bound(int t,int start,int end ,int[] A){       
        while(start<=end){
             int mid = (start+end)/2;
             if(A[mid]>=t){
                  end = mid -1;
             }else{
                  start = mid+1;
             }
        }
        return start;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值