leetcode刷题:数组01 (二分查找)

52 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 力扣题目链接

给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。

示例 1:

输入: nums = [-1,0,3,5,9,12], target = 9     
输出: 4       
解释: 9 出现在 nums 中并且下标为 4     

示例 2:

输入: nums = [-1,0,3,5,9,12], target = 2     
输出: -1        
解释: 2 不存在 nums 中因此返回 -1        

提示:

  • 你可以假设 nums 中的所有元素是不重复的。
  • n 将在 [1, 10000]之间。
  • nums 的每个元素都将在 [-9999, 9999]之间。
package com.programmercarl.array;

/**
 * @ClassName BinarySearch
 * @Descriotion https://leetcode-cn.com/problems/binary-search/
 * @Author nitaotao
 * @Date 2022/5/1 11:52
 * @Version 1.0
 * 704. 二分查找
 **/
public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
        System.out.println(search(nums,13));
    }

    public static int search(int[] nums, int target) {
        // 考虑不存在的情况,目标值比最小值小 或 比最大值大
        if (target < nums[0] || (target > nums[nums.length - 1])) {
            return -1;
        }
        return binarySearch(nums, 0, nums.length, target);
    }

    public static int binarySearch(int[] nums, int start, int end, int target) {
        if (start > end) {
            return -1;
        }
        //1.中间值
        int mid = (end + start) / 2;
        if (target < nums[mid]) {
            return binarySearch(nums, start, mid - 1, target);
        } else if (target > nums[mid]) {
            return binarySearch(nums, mid + 1, end, target);
        } else {
            return mid;
        }
    }
}

在这里插入图片描述

class Solution {
     public  int search(int[] nums, int target) {
          if (nums[0] > target || nums[nums.length - 1] < target) {
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        //1.中间值
        int mid = (end- start) / 2;
        while (start <= end) {
            if (target < nums[mid]) {
                end = mid - 1;
            } else if (target > nums[mid]) {
                start = mid + 1;
            } else {
                return mid;
            }
             mid = (end + start) / 2;
        }
        return -1;
    }
}

在这里插入图片描述