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

记录

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

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

代码

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));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值