当前位置:网站首页>Remember the interview algorithm of a company: find the number of times a number appears in an ordered array

Remember the interview algorithm of a company: find the number of times a number appears in an ordered array

2022-07-06 11:00:00 Sanli akaman

Record

Remember the interview algorithm of a company : Find the number of times a number appears in an ordered array , The requirement is not to use violent cracking ;

I knew how to do it , As a result, I couldn't write two points, so I couldn't tear it out , It's really enough ..

Code

package com.vleus.algorithm.strings;

/** * @author vleus * @date 2021 year 09 month 26 Japan  20:26 */
public class GetNumCount {
    

// public static int getNumCount(int[] array, int num) {
    
//
// if (array.length == 0) {
    
// return 0;
// }
//
// int count = 0;
// for (int i = 0; i < array.length; i++) {
    
// if (array[i] == num) {
    
// count++;
// }
// }
//
// return count;
// }

    // Two points search 
    private static int times(int[] arr, int n) {
    
        int low = 0;
        int high = arr.length - 1;
        while (low < high) {
    
            int mid = low + (high - low) / 2;
            if (arr[mid] >= n) {
    
                high = mid;
            } else {
    
                low = mid + 1;
            }
        }
        return low;
    }

    public static int getNumCount2(int[] arr, int num) {
    
        int first = times(arr, num);
        int last = times(arr, num + 1);

        int times = (first == arr.length || arr[first] != num) ? 0 : last - first;

        return times;
    }

    public static void main(String[] args) {
    
        int[] arr = {
    1, 2, 3, 3, 3, 4, 5};
        System.out.println(getNumCount2(arr,6));
    }

}
原网站

版权声明
本文为[Sanli akaman]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912266731.html