248. Count of Smaller Number

本文介绍了一种算法,用于计算整数数组中小于特定查询值的元素数量。通过遍历数组和利用哈希表来提高查询效率,适用于多种编程挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Example

Example 1:

Input: array =[1,2,7,8,5] queries =[1,8,5]
Output:[0,4,2]

Example 2:

Input: array =[3,4,5,8] queries =[2,4]
Output:[0,1]

Challenge

Could you use three ways to do it.

  1. Just loop
  2. Sort and binary search
  3. Build Segment Tree and Search.

import java.util.*;

public class Solution {
    /**
     * @param A: An integer array
     * @param queries: The query list
     * @return: The number of element in the array that are smaller that the given integer
     */
    public List<Integer> countOfSmallerNumber(int[] A, int[] queries) {
        // write your code here
        
        List<Integer> returnvalue = new ArrayList<Integer>();
        Hashtable<Integer, Integer> existTable = new Hashtable<Integer,Integer>();
        
        for(int i =0;i<queries.length;i++){
            int count = 0;
            int temp = queries[i];
            if(existTable.containsKey(temp)){
                 returnvalue.add(existTable.get(temp));
                 
            }
            else{
                    for(int j =0; j<A.length;j++){
                    if(A[j]<temp){
                        count++;
                    }
                }
                 returnvalue.add(count);
                 
            }
            
           
        }
        return returnvalue;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值