[Leetcode] 35. Search Insert Position

更新於 發佈於 閱讀時間約 2 分鐘

題目 : 35. 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


1.

list.index(x)方法 : 在list中找出第一個和x值匹配的索引位置值


class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
#如果target有出現在nums中,用index()方法回傳索引值
if target in nums:
return nums.index(target)
#找出比target大的數值,如果target < nums[i],就回傳nums[i]的索引值i
for i in range(len(nums)):
if target < nums[i]:
return i
#如果target是nums中最大值,則nums最大索引值為len(nums)
return len(nums)


留言
avatar-img
留言分享你的想法!
avatar-img
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
Youna's Devlog的其他內容
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/02/13
題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 100. Same Tree
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
2024/01/11
題目 : 83. Remove Duplicates from Sorted List
Thumbnail
看更多
你可能也想看
Thumbnail
題目敘述 Sort Array by Increasing Frequency Leetcode #1636 給定一個輸入陣列,請依照出現頻率的多寡從低頻到高頻排列陣列元素。 如果有兩個元素的出現頻率相同,依照元素大小從大到小排列。 測試範例 Example 1: Input: nums
Thumbnail
題目敘述 Sort Array by Increasing Frequency Leetcode #1636 給定一個輸入陣列,請依照出現頻率的多寡從低頻到高頻排列陣列元素。 如果有兩個元素的出現頻率相同,依照元素大小從大到小排列。 測試範例 Example 1: Input: nums
Thumbnail
Leetcode 精選75題 題目與題解 熱門考點 目錄 (持續更新中) 建議從左側目錄 或者 按Ctrl+F輸入關鍵字進行搜尋
Thumbnail
Leetcode 精選75題 題目與題解 熱門考點 目錄 (持續更新中) 建議從左側目錄 或者 按Ctrl+F輸入關鍵字進行搜尋
Thumbnail
給定一個輸入非負整樹陣列nums,請找出k值,使得陣列中恰好有k個元素大於等於 k。如果無解,回傳-1。尋找k值的方法包括排序法和二分搜尋法,時間複雜度都為O(n log n),空間複雜度為O(1)。關鍵知識點是當解空間具有遞增或遞減的性質時,可以用二分搜尋法加快搜尋效率。
Thumbnail
給定一個輸入非負整樹陣列nums,請找出k值,使得陣列中恰好有k個元素大於等於 k。如果無解,回傳-1。尋找k值的方法包括排序法和二分搜尋法,時間複雜度都為O(n log n),空間複雜度為O(1)。關鍵知識點是當解空間具有遞增或遞減的性質時,可以用二分搜尋法加快搜尋效率。
Thumbnail
魔鬼藏在二分搜尋裡!輸出值代表的意含、題意產生的邊界條件,寫完模板才是挑戰的開始 Orz
Thumbnail
魔鬼藏在二分搜尋裡!輸出值代表的意含、題意產生的邊界條件,寫完模板才是挑戰的開始 Orz
Thumbnail
題目敘述 題目會給定兩個輸入。 第一個輸入是關鍵字清單products,第二個是使用者輸入的字串searchWord。 要求我們實現關鍵字搜尋建議系統,使用者每輸入一個字元就推薦一次。 推薦時,優先返回字典序(Lecial order)最接近的關鍵字,最多不要超過三個關鍵字。 題目的原文
Thumbnail
題目敘述 題目會給定兩個輸入。 第一個輸入是關鍵字清單products,第二個是使用者輸入的字串searchWord。 要求我們實現關鍵字搜尋建議系統,使用者每輸入一個字元就推薦一次。 推薦時,優先返回字典序(Lecial order)最接近的關鍵字,最多不要超過三個關鍵字。 題目的原文
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 27. Remove Element
Thumbnail
題目 : 88. Merge Sorted Array
Thumbnail
題目 : 88. Merge Sorted Array
Thumbnail
題目 : 35. Search Insert Position
Thumbnail
題目 : 35. Search Insert Position
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News