lintcode(248)统计比给定整数小的数的个数

来源:互联网 发布:手机手柄映射软件 编辑:程序博客网 时间:2024/05/23 19:14

Description:

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

 注意事项

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

Explanation:

样例

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

Solution:

仅用循环实现 ,先排序会降低时间复杂度

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        ArrayList<Integer> result = new ArrayList<Integer>();        Arrays.sort(A);                for(int i = 0;i<queries.length;i++){            int count = 0;            for(int j = 0;j<A.length;j++){                if(A[j] >= queries[i]){                    count = j;                    break;                }            }            result.add(count);        }        return result;    }}



阅读全文
0 0
原创粉丝点击