记某公司面试算法题:查找一个有序数组某个数字出现的次数

Posted 三笠·阿卡曼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记某公司面试算法题:查找一个有序数组某个数字出现的次数相关的知识,希望对你有一定的参考价值。

记录

记某公司面试算法题:查找一个有序数组某个数字出现的次数,要求是不能使用暴力破解的方式;

本来知道怎么做,结果因为不会写二分导致没手撕出来,着实够菜的。。

代码

package com.vleus.algorithm.strings;

/**
 * @author vleus
 * @date 2021年09月26日 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;
//    

    //二分查找
    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));
    


以上是关于记某公司面试算法题:查找一个有序数组某个数字出现的次数的主要内容,如果未能解决你的问题,请参考以下文章