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

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

样例

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

注意

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

挑战

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

  1. 仅用循环方法

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

  3. 构建 线段树 和 搜索

分析:这题没有必要用线段树,写起来多麻烦,可以直接二分查找,代码简洁才是王道啊

代码:

class Solution {
public:
   /**
     * @param A: An integer array
     * @return: The number of element in the array that 
     *          are smaller that the given integer
     */
    vector<int> countOfSmallerNumber(vector<int> &A, vector<int> &queries) {
        // write your code here
        sort(A.begin(),A.end());
        vector<int> ret;
        for(int q:queries)
        {
            int cnt = lower_bound(A.begin(),A.end(),q)-A.begin();
            ret.push_back(cnt);
        }
        return ret;
    }
};
    原文作者:LintCode题目解答
    原文地址: https://blog.csdn.net/wangyuquanliuli/article/details/45725175
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞