栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

记录

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

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

代码
package com.vleus.algorithm.strings;


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

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/271200.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号