Number of occurrences of numbers in a sorted array title description
Counts the number of occurrences of a number in a sorted array.
Ideas
- To handle an array that has been ordered, consider the idea of binary search
- Find the first position of this number with a binary search, and then find the last position that appears, you can get this number several times, so the time complexity is O (LOGN)
- Note that the number does not appear in the array
Code
PublicClass Solution {PublicIntGetnumberofk(int []Array,int k) {int num =0;if (Array = = NULL | |Array.Length = =0) {return num; }int FIRSTK = GETFIRSTK (Array, K,0,Array.Length-1);int LASTK = GETLASTK (Array, K,0,Array.Length-1); System.out.println ("First:" + FIRSTK +"LASTK:" + LASTK);if (Firstk >-1 && lastk >-1) {return LASTK-FIRSTK +1; }return num; }PublicIntGetfirstk(int[] Data,int k,int start,int end) {if (Start > End) {Return-1; }int Midindex = (start + end)/2;int middata = Data[midindex];if (Middata = = k) {if (Midindex >0 && Data[midindex-1]! = k) | | Midindex = =0) {return midindex; }else {end = Midindex-1; } }Elseif (Middata > k) {end = Midindex-1; }else {start = Midindex +1; }return Getfirstk (data, K, start, end); }PublicIntGetlastk(int[] Data,int k,int start,int end) {if (Start > End) {Return-1;} int Midindex = (start + end)/2; int middata = Data[midindex]; if (Middata = k) {if (Midindex < data.length-1 && data[midindex + 1]! = k) | | Midindex = = data.length-1) {return Midindex;} else {start = Midindex + 1;}} else if (Middata > k) {end = Midindex-1; } else {start = Midindex + 1;} return getlastk (data, K, start, end);}}
Number of occurrences of a number in a sorted array-Sword point offer