NYUer | LeetCode704 Binary Search

LeetCode704 Binary Search


Author: Stefan Su
Create time: 2022-10-26 02:11:25
Location: New York City, NY, USA

Description Easy

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
Constrains
  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All the integers in nums are unique
  • nums is sorted in ascending order

Analysis

First, we should know what binary search is. It is a search algorithm for a sorted array to find the index of a given target value. Generally, we do operation in the array’s indices. We can consider this problem in two ways. [left, right] or [left, right).

Remember, always pay attention on the while condition and the move of index in the while loop.

Solution

  • [left, right] version
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # [left, right]
        left = 0
        right = len(nums) - 1
        while left <= right: # we consider nums[left] == nums[right] is meaningful, so use <=
            middle = int((left + right) / 2)
            if nums[middle] < target:
                left = middle + 1  # key operation
            elif nums[middle] > target:
                right = middle - 1  # key operation
            else:
                return middle
        return -1
  • [left, right) version
class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        # [left, right)
        left = 0
        right = len(nums)
        while left < right:  # we consider nums[len(nums)] is out of index
            middle = int((left + right) / 2)
            if nums[middle] < target:
                left = middle + 1  # key operation
            elif nums[middle] > target:
                right = middle  # key operation
            else:
                return middle
        return -1

Hopefully, this blog can inspire you when solving LeetCode704. For any questions, please comment below.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值