[Leetcode] 35. Search Insert Position

[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
Youna's Devlog
7會員
49內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言
avatar-img
留言分享你的想法!
Youna's Devlog 的其他內容
題目 : 121. Best Time to Buy and Sell Stock
題目 : 100. Same Tree
題目 : 83. Remove Duplicates from Sorted List
題目 : 121. Best Time to Buy and Sell Stock
題目 : 100. Same Tree
題目 : 83. Remove Duplicates from Sorted List