【知识积累】在一个有序数组中,找>=某个数最左侧的位置

package com.example.demo.algorithm;

/**
 * @Description :
 * 在一个有序数组中,找>=某个数最左侧的位置
 * 举例:1111222233334444555
 * 数字:2
 * 最左侧的位置:1111(2)
 *
 * 111122223-3-334444555
 *           2
 * 11112-2-2233
 *       2
 * 11-1-122
 *    2
 *    11-2-2
 *       2
 * @Author : Darren
 * @Date : 2021 年 02 月 07 日 20:06:18
 * @since : 1.0
 */
public class J005_BSNearLeft {

    public static void main(String[] args) {
        int count = 500000;
        int maxSize = 100;
        int maxValue = 100;
        int num = 8;
        boolean success = true;
        for (int i = 0; i < count; i++) {
            int[] arrays = J001_SelectSort.generateRandomArray(maxSize, maxValue);
            //数组排序
            J001_SelectSort.comparator(arrays);
            if (bsNearLeft(arrays, num) != bsNearLeftByIntrinsic(arrays, num)){
                success = false;
                J001_SelectSort.printArray(arrays);
                break;
            }
        }
        System.out.println(success ? "success" : "failure");
    }

    public static int bsNearLeft(int[] arrays, int num){
        int l = 0;
        int r = arrays.length - 1;
        int index = -1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            if (arrays[mid] >= num) {
                r = mid - 1;
                index = mid;
            } else {
                l = mid + 1;
            }
        }
        return index;

    }

    /**
     * java 自带判断一个数在数组中出现的第一个位置的下标
     * @param arrays
     * @param num
     * @return
     */
    public static int bsNearLeftByIntrinsic(int[] arrays, int num){
        //长流boxed()返回一个由该流的元素组成的Stream,每个元素都装箱成Integer。
        /*List<Integer> list = Arrays.stream(arrays).boxed().collect(Collectors.toList());
        return list.indexOf(num);*/

        //误解
        //最左侧的位置 不一定相等,也就是说不一定包含
        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i] >= num) {
                return i;
            }
        }
        return -1;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值