The title

Given an ordered (ascending) integer array nums with n elements and a target value, write a function to search for target in NUMs, returning a subscript if the target value exists, and -1 otherwise.

Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 appears in nums with subscript 4 Example 2: Input: Nums = [-1,0,3,5,9,12], target = 2Copy the code

Tip:

You can assume that all elements in NUMS are not repeated. N will be between [1, 10000]. Each element of nums will be between [-9999, 9999].

Their thinking

class Solution: def search(self, nums: List[int], target: int) -> int: Len (nums)-1 while left <= right: len(nums)-1 mid = (left+right)//2 # print(left,mid,right) if nums[mid] == target: return mid elif nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 return -1 if __name__ == '__main__': # nums = [-1,0,3,5,9,12] # target = 2 5] target = 5 result = Solution().search(nums, target) print(result)Copy the code