統計比給定整數小的數的個數
給定一個整數數組 (下標由 0 到 n-1,其中 n 表示數組的規模,數值範圍由 0 到 10000),以及一個 查詢列表。對於每一個查詢,將會給你一個整數,請你返回該數組中小於給定整數的元素的數量。
對於數組 [1,2,7,8,5]
,查詢 [1,8,5]
,返回 [0,4,2]
可否用一下三種方法完成以上題目。
-
僅用循環方法
-
分類搜索 和 二進制搜索
-
構建 線段樹 和 搜索
相關題目 Expand
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;
}
}