• 二分查找


    class Solution {
    public static void main(String[] args) {
    // System.out.println(new Solution().find132pattern(new int[]{7, 6, 5, 1, 2, 4, 3}));
    int[] arr = {1, 2, 2, 2, 2, 3, 3, 4,5,5,5};
    System.out.println(new Solution().left_bound(arr, 1));
    System.out.println(new Solution().left_bound2(arr, 1));
    System.out.println(new Solution().right_bound(arr, 1));
    System.out.println(new Solution().right_bound2(arr, 1));
    System.out.println(new Solution().binarySearch(arr, 1));
    }

    int left_bound(int[] nums, int target) {
    if (nums.length == 0) {
    return -1;
    }
    int left = 0;
    int right = nums.length; // 注意

    while (left < right) { // 注意
    int mid = (left + right) / 2;
    if (nums[mid] == target) {
    right = mid;
    } else if (nums[mid] < target) {
    left = mid + 1;
    } else if (nums[mid] > target) {
    right = mid; // 注意
    }
    }
    return left;
    }
    int left_bound2(int[] nums, int target) {
    if (nums.length == 0) {
    return -1;
    }
    int left = 0;
    int right = nums.length-1; // 注意

    while (left <= right) { // 注意
    int mid = (left + right) / 2;
    if (nums[mid] == target) {
    right = mid-1;
    } else if (nums[mid] < target) {
    left = mid + 1;
    } else if (nums[mid] > target) {
    right = mid-1; // 注意
    }
    }
    return left;
    }

    int right_bound(int[] nums, int target) {
    if (nums.length == 0) {
    return -1;
    }
    int left = 0, right = nums.length;

    while (left < right) {
    int mid = (left + right) / 2;
    if (nums[mid] == target) {
    left = mid + 1; // 注意
    } else if (nums[mid] < target) {
    left = mid + 1;
    } else if (nums[mid] > target) {
    right = mid;
    }
    }
    return left - 1; // 注意
    }
    int right_bound2(int[] nums, int target) {
    if (nums.length == 0) {
    return -1;
    }
    int left = 0, right = nums.length-1;

    while (left <= right) {
    int mid = (left + right) / 2;
    if (nums[mid] == target) {
    left = mid+1; // 注意
    } else if (nums[mid] < target) {
    left = mid+1;
    } else if (nums[mid] > target) {
    right = mid-1;
    }
    }
    return left-1; // 注意
    }

    int binarySearch(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1; // 注意

    while (left <= right) { // 注意
    int mid = (right + left) / 2;
    if (nums[mid] == target) {
    return mid;
    } else if (nums[mid] < target) {
    left = mid + 1; // 注意
    } else if (nums[mid] > target) {
    right = mid - 1; // 注意
    }
    }
    return -1;
    }
    }
    参考:https://www.zhihu.com/question/36132386/answer/712269942
  • 相关阅读:
    PC端圣诞树下载
    win7开机一直在正在启动windows界面怎么办?
    EFI、UEFI、MBR、GPT的区别
    进入BIOS中,设置U盘启动
    CSS3摆动动画效果
    比特币钱包搭建与使用
    自动校时工具
    windows7蓝屏0x000000c4
    如何使用webpack打包你的项目
    开源货币/比特币Multiminer、bitrade、bitcoinjs-lib、python-bitcoinrpc介绍
  • 原文地址:https://www.cnblogs.com/xufan/p/14600300.html
Copyright © 2020-2023  润新知