目录

Leetcode34二分查找

Leetcode:34(二分查找)

一,题目

https://i-blog.csdnimg.cn/direct/f71aee7464834bc7ba6d293e916f6523.png

二,思路

  • 找到最左和最右俩个点,利用俩个二分查找
  • 俩种情况一种存在一种不存在
  • 存在:nums[m]==target右边-1  结果i
  • 存在:nums[m]==target左边+1  但是结果下标减去i-1
  • 上面俩种情况可以举例子 1 2 2 3 找2 自己推理一下就明白
  • 不存在:一种情况nums为空的情况 一种是数据没找到

三,代码

import java.util.Arrays;

public class Leetcode34 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Leetcode34().searchRange(new int[]{1}, 1)));
    }

    public int[] searchRange(int[] nums, int target) {
        int[] arr = new int[2];
        arr[0] = left(nums, target);
        if (arr[0] == -1)
            arr[1] = -1;
        else
            arr[1] = right(nums, target);
        return arr;
    }

    public int left(int[] nums, int target) {
        if (nums.length > 0) {
            int i = 0;
            int j = nums.length - 1;
            while (i <= j) {
                int m = (i + j) >>> 1;
                if (nums[m] < target) {//左
                    i = m + 1;
                } else {
                    j = m - 1;
                }
            }
            if (i < nums.length && nums[i] == target) return i;
        }
        return -1;
    }

    public int right(int[] nums, int target) {
        if (nums.length > 0) {
            int i = 0;
            int j = nums.length - 1;
            while (i <= j) {
                int m = (i + j) >>> 1;
                if (nums[m] <= target) {//左
                    i = m + 1;
                } else {
                    j = m - 1;
                }
            }
            if (i - 1 < nums.length && nums[i - 1] == target) return i - 1;
        }
        return -1;
    }
}