zoukankan      html  css  js  c++  java
  • Count of Smaller Number

    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 that the given integer.

    hint: 

    Solution 1

      Quick Sort + Binary Search

    Solution 2

      Segment Tree

     1 public class Smaller {
     2     
     3         public ArrayList<Integer> countOfSmallerNumber(int[] A, int[] queries) {
     4             ArrayList<Integer> list = new ArrayList<Integer>();
     5             if (queries == null || queries.length == 0)
     6                 return list;
     7             if(A == null || A.length == 0) {
     8                 for (int i = 0; i < queries.length; i++) {
     9                     list.add(0);
    10                 }
    11                 return list;
    12             }
    13 
    14             sort(A, 0, A.length-1);
    15             
    16             for (int i = 0; i < queries.length; i++) {
    17                 list.add(binary(A, queries[i]));
    18             }
    19             System.out.println(list);
    20             return list;
    21         }
    22         
    23         public int binary(int[] A, int k) {
    24             int i = 0, j = A.length-1;
    25             while (i <= j) {
    26                 int mid = (j - i) / 2 + i;
    27                 if (A[mid] >= k) j = mid - 1;
    28                 else i = mid + 1;
    29             }
    30             return i;
    31         }
    32         
    33         public void sort(int[] A, int start, int end) {
    34             if (start >= end) return;
    35             int i = start, j = end;
    36             int tmp = A[start];
    37             while (i < j) {
    38                 while (i < j && A[j] >= tmp) j--;
    39                 A[i] = A[j];
    40                 while (i < j && A[i] < tmp) i++;
    41                 A[j] = A[i];
    42             }
    43             A[i] = tmp;
    44             sort(A, start, i-1);
    45             sort(A, i+1, end);
    46         }
    47         public static void main(String[] args) {
    48             Smaller sol = new Smaller();
    49             int[] A = {55,81,56,91,35,92,10,53,27,94,64,45,19,44,52,19,79,12,16,90,97,33,73,2,20,68,19,7,17,62,45,48,62,26,85,4,63,67,56,16};
    50             int[] queries = {10,43,2,17,28,75,75,12};
    51             sol.countOfSmallerNumber(A, queries);
    52         }
    53     }
  • 相关阅读:
    最小费用最大流问题
    成大事必备9种能力、9种手段、9种心态
    转 fpga学习经验2
    算法 FFT理论1
    FPGA进阶之路1
    FPGA:亲和力激活竞争力
    1030 又回来了
    转 fpga学习经验1
    调查:近半大学生愿接受15002000元月薪
    转 观点:哪些人适合做FPGA开发(精华)
  • 原文地址:https://www.cnblogs.com/joycelee/p/4516165.html
Copyright © 2011-2022 走看看