欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

力扣704 - Binary Search 二分查找

程序员文章站 2022-03-09 15:24:32
...

力扣704 - Binary Search 二分查找

题目描述

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.

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

典型的二分查找题, 需要注意的是区间问题和边界值

代码

  1. 最简单但是效率差的python解法:
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if target in nums:
            return nums.index(target)
        else:
            return -1
  1. 因为最近在学java,就用java解题了。

正确的二分查找算法:

class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length -1;
        while (left <= right){
            int mid = (left + right)/2;
            // found
            if (nums[mid] == target){
                return mid;
            }
            //中间比target小,往右搜
            else if (nums[mid] < target)
                left = mid + 1; //注意区间问题
            else if (nums[mid] >= target)
                right = mid -1 ;     
        }
        //没找到
        return -1;
    }
}
相关标签: Leetcode