[Sword refers to offer] The number of times the number appears in the ascending array

Title Description
Count the number of times a number appears in the ascending array.

示例1
输入
[1,2,3,3,3,3,4,5],3
返回值
4

solution:

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

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/114553912