Sword refers to offer—53. The number of times a number appears in a sorted array—Analysis and code (Java)

Sword refers to offer-53. The number of times the number appears in the sorted array-analysis and code [Java]

1. Title

Count the number of times a number appears in the sorted array.

Two, analysis and code

1. Binary search

(1) Thinking

Because the topic is a sorted array, you can combine the idea of ​​binary search to find the first and last positions of the corresponding numbers in the array, and calculate the number of times.

(2) Code

public class Solution {
    
    
    public int GetNumberOfK(int [] array , int k) {
    
    
        if (array == null || array.length == 0 || k < array[0] || k > array[array.length - 1])
           return 0;
        int left, right;
        if (array[0] == k)
            left = -1;
        else
            left = BiSearch(array, k - 1, 0, array.length);
        if (array[array.length - 1] == k) 
            right = array.length - 1;
        else 
            right = BiSearch(array, k, left, array.length);
        return right - left;
    }
    
    public int BiSearch(int [] array, int k, int l, int r) {
    
    
        int m;
        while (l < r - 1) {
    
    
            m = (l + r) >> 1;
            if (array[m] <= k)
                l = m;
            else
                r = m;
        }
        return l;
    }
}

(3) Results

Running time: 13ms, occupied memory: 9296k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/110942434