題目 : 35. Search Insert Position
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)