iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 70

[Day 67 - 1] Search Insert Position (Easy)

  • 分享至 

  • xImage
  •  

35. Search Insert Position

Solution 1: Binary Search

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        lft = 0
        rht = len(nums) - 1
        while lft <= rht:
            mid = lft + (rht - lft) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                lft = mid + 1
            elif nums[mid] > target:
                rht = mid - 1
        return lft

Time Complexity: O(log(n))
Space Complexity: O(1)

Reference

https://leetcode.com/problems/search-insert-position/discussion/

Follow-up

  1. First Bad Version

上一篇
[Day 66] Perfect Squares (Medium)
下一篇
[Day 67 - 2] Swap Nodes in Pairs (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言