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(logn) 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
classSolution:defsearchRange(self,nums: List[int],target:int) -> List[int]:defsearch_first(): low, high =0,len(nums)-1while low <= high: mid = (low + high) //2# If hitif nums[mid]== target:if mid ==0or nums[mid -1]!= target:return mid# If nums[mid] is not the first occurrence,# search the lower intervalelse: high = mid -1elif nums[mid]> target: high = mid -1else: low = mid +1return-1defsearch_last(): low, high =0,len(nums)-1while low <= high: mid = (low + high) //2# If hitif nums[mid]== target:if mid ==len(nums)-1or nums[mid +1]!= target:return mid# If nums[mid] is not the last occurrence,# search the higher intervalelse: low = mid +1elif nums[mid]> target: high = mid -1else: low = mid +1return-1 first =search_first() last =search_last()return [first, last]
Find Smallest Letter Greater Than Target (LeetCode 744)
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"