LeetCode Search Insert Position
Search Insert Position for solving LeetCode Problems
Original question
In an ordered array, if the target number exists, its subscript is returned; otherwise, the Base Value of the inserted position is returned.
Note:
No repeated numbers in the array
Example:
Input: nums = [1, 3, 5, 6], target = 5
Output: 2
Input: nums = [1, 3, 5, 6], target = 2
Output: 1
Solutions
It is also a binary search question. If the current number is a target number or the current number is greater than the target number and the previous number is smaller than the target number, the current subscript is returned; if the current number is the last one and is smaller than the target number, the last digit of the current base is returned.
AC Source Code
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ length = len(nums) start = 0 end = length while start < end: mid = (start + end) // 2 if nums[mid] == target or (nums[mid] > target and (mid == 0 or nums[mid - 1] < target)): return mid if mid == length - 1 and nums[mid] < target: return mid + 1 if nums[mid] < target: start = mid + 1 else: end = midif __name__ == "__main__": assert Solution().searchInsert([1, 3, 5, 6], 5) == 2 assert Solution().searchInsert([1, 3, 5, 6], 2) == 1 assert Solution().searchInsert([1, 3, 5, 6], 7) == 4 assert Solution().searchInsert([1, 3, 5, 6], 0) == 0
Please check out my Github for relevant source code.