Title Description
Statistics the number of times a number appears in a sorted array.
Solving problems
The normal way of thin k ing is dichotomy search. We use recursive method to find the subscript that appears for the first time and circular method to find the subscript that appears for the last time.
In addition, there is another wonderful idea, because data is an integer, so we do not need to search for the two positions of k, but directly search for the positions of k-0.5 and k+0.5 which should be inserted, and then subtract.
Reference code
Law 1:
//Ordinary loop lookup public class Solution { public static int GetNumberOfK(int [] array , int k) { int flag = 0; for (int i : array) { if(k==i){ flag++; } } return flag; } public static void main(String[] args) { int [] input = {2,8,1,5,9,2}; System.out.println(Solution.GetNumberOfK(input,2)); } }
//Two points search public class Solution { public static int GetNumberOfK(int [] array , int k) { int len = array.length; if(len == 0) return 0; int first = getFirst(array, k, 0, len-1); int last = getLast(array, k, 0, len-1); if(first != -1 && last != -1){ return last - first + 1; } return 0; } public static int getFirst(int [] array, int k, int start, int end){ int mid; while(start <= end){ mid = start + (end - start) / 2; if(k <= array[mid]) end = mid - 1; else start = mid + 1; } if(start < array.length && array[start] == k) return start; else return -1; } // loop public static int getLast(int [] array, int k, int start, int end){ int mid; while(start <= end){ mid = start + (end - start) / 2; if(k >= array[mid]) start = mid + 1; else end = mid - 1; } if(end >= 0 && array[end] == k) return end; else return -1; } public static void main(String[] args) { int [] input = {2,8,1,5,9,2}; System.out.println(Solution.GetNumberOfK(input,2)); } }
Law 2:
public class Solution { public int GetNumberOfK(int [] array , int k) { return biSearch(array, k+0.5) - biSearch(array, k-0.5); } public int biSearch(int [] array, double k){ int start = 0, end = array.length - 1; while(start <= end){ int mid = start + (end - start)/2; if(array[mid] > k){ end = mid - 1; }else{ start = mid + 1; } } return start; } }