35.Search Insert Position === ###### tags: `Easy`,`Array`,`Binary Search` [35. Search Insert Position](https://leetcode.com/problems/search-insert-position/) ### 題目描述 Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. ### 範例 **Example 1:** ``` Input: nums = [1,3,5,6], target = 5 Output: 2 ``` **Example 2:** ``` Input: nums = [1,3,5,6], target = 2 Output: 1 ``` **Example 3:** ``` Input: nums = [1,3,5,6], target = 7 Output: 4 ``` **Constraints**: * 1 <= `nums.length` <= 10^4^ * -10^4^ <= `nums[i]` <= 10^4^ * `nums` contains **distinct** values sorted in **ascending** order. * -10^4^ <= `target` <= 10^4^ ### 解答 #### Python ```python= class Solution: def searchInsert(self, nums: List[int], target: int) -> int: L, R = 0, len(nums) - 1 while L <= R: M = (L + R) // 2 if nums[M] == target: return M if target < nums[M]: R = M - 1 else: L = M + 1 return R + 1 ``` > [name=Yen-Chi Chen][time=Mon, Feb 20, 2023] ```python= class Solution: def searchInsert(self, nums: List[int], target: int) -> int: return bisect_left(nums, target) ``` > [name=Yen-Chi Chen][time=Mon, Feb 20, 2023] ```python= class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) while l < r: mid = l + (r - l) // 2 if nums[mid] >= target: r = mid else: l = mid + 1 return l ``` > [name=Ron Chen][time=Wed, Feb 22, 2023] #### Javascript ```javascript= function searchInsert(nums, target) { let max = nums.length - 1; let min = 0; while (min <= max) { const position = ~~((max + min) / 2); if (nums[position] === target) return position; if (nums[position] > target) { max = position - 1; } else { min = position + 1; } } return max + 1; } ``` > [name=Masrgoat][time=Mon, Feb 20, 2023] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)