704 binary search

Title: Given a n elements ordered (ascending) nums array of integers and a target value target, a write function in nums search target, if the index target values returned, otherwise -1.
Link: https: //leetcode-cn.com/problems/binary-search

Act One: two ways to reference written by someone else

Ideas: very basic question of a binary search, using two methods, one left close right close a left and right to open and close, can be achieved, the two approaches may need to be improved in a number of complex issues, but the basic framework constant,

from typing import List
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        # 由于nums的长度至少为1,所以无需提前判断
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) >> 1
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            elif nums[mid] < target:
                left = mid + 1
        return -1

from typing import List
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums)
        while left < right:
            mid = (left + right) >> 1
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid
            elif nums[mid] < target:
                left = mid + 1
        return -1
if __name__ == '__main__':
    solution = Solution()
    # result = solution.search(nums = [-1,0,3,5,9,12], target = 2)
    result = solution.search(nums = [2,5], target = 5)
    print(result)
View Code

ttt

 

Guess you like

Origin www.cnblogs.com/xxswkl/p/12354477.html