JZ37 Number of times the number appears in the sorted array

Title description

Count the number of times a number appears in an ascending array.

Code

public class Solution {
    
    
    public int GetNumberOfK(int [] array , int k) {
    
    
        int low = 0;
        int high = array.length-1;
        int mid = (low+high)/2;
        int count = 0;
        while (high-low == 1 ){
    
    
            if (array[mid] > k) {
    
    
                high = mid;
            }else if (array[mid] < k){
    
    
                low = mid;
            }else {
    
    
                break;
            }
            mid = (low+high)/2;
        }
        for (int i = low; i <= high; i++) {
    
    
            if (array[i] == k) {
    
    
                count++;
            }
        }
            return count;
    }

}

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/108493336