# 35. Search Insert Position #### Difficulty: Easy link: https://leetcode.com/problems/search-insert-position/ ### 1. Binary Search #### $O(log\ n)$ runtime, $O(1)$ space 題目限制$O(log\ n)$複雜度,所以想到用binary search,套用binary search模板如下。 ##### python ```python= class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left, right = 0, len(nums) while left < right: mid = left + (right - left) // 2 if nums[mid] >= target: right = mid else: left = mid + 1 return left ``` 或著,使用bisect套件。 ```python= import bisect class Solution: def searchInsert(self, nums: List[int], target: int) -> int: return bisect.bisect_left(nums, target) ``` ###### tags: `leetcode`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up