标签:
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 }
标签:
原文地址:http://www.cnblogs.com/joycelee/p/4516165.html