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;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章