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     }

 

转载于:https://www.cnblogs.com/joycelee/p/4516165.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值