0
点赞
收藏
分享

微信扫一扫

Java描述 LeetCode,704. Binary Search 二分查找,原来二分查找也可以有小优化~

穿裙子的程序员 2022-01-08 阅读 20

1-1:题目描述

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.

1-2:递归解法

不多说,直接上代码。递归作为基础代码,应该都会写的。

public int search(int[] nums, int target) {
    int n = nums.length;
    return recursion(nums, 0, n - 1, target);
}

public int recursion(int[] nums, int first, int last, int target) {
    if (first > last) {
        return -1;
    }
    int mid = (first + last)/2;
    if (nums[mid] > target) {
        return recursion(nums, first, mid - 1, target);
    }
    if (nums[mid] < target) {
        return recursion(nums, mid + 1, last, target);
    }
    return mid;
}

很平淡无奇,但是你再看下面的这一段代码!对比以下,你会发现原来二分查找也会有优化!

public int search(int[] nums, int target) {
    int n = nums.length;
    // 1. 如果不在这个范围之内,就可以直接return-1了。
    if (target < nums[0] || target > nums[n - 1]) {
        return -1;
    }
    return recursion(nums, 0, n - 1, target);
}

public int recursion(int[] nums, int first, int last, int target) {
    if (first > last) {
        return -1;
    }
    // 2. 防止int + int 溢出
    int mid = first + (last - first) >> 2;
    if (nums[mid] > target) {
        return recursion(nums, first, mid - 1, target);
    }
    if (nums[mid] < target) {
        return recursion(nums, mid + 1, last, target);
    }
    return mid;
}

别小瞧这些细节小优化,你写出来了,你就比别人好一点点。很多个一点点,就是许多了!

1-3:迭代解法

public int searchIteration(int[] nums, int target) {
    int n = nums.length;
    if (target < nums[0] || target > nums[n - 1]) {
        return -1;
    }

    int first = 0;
    int last = nums.length - 1;
    while (first <= last) {
        int mid = first + (last - first) / 2;
        if (nums[mid] > target) {
            last = mid - 1;
        } else if (nums[mid] < target) {
            first = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

在这里插入图片描述

举报

相关推荐

0 条评论