題目:給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。 你可以假設數組中無重復元素。
思路:題目比較簡單
程序:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
length = len(nums)
result = 0
index = 0
while index < length:
if nums[index] > target:
result = index
break
elif nums[index] == target:
result = index
break
else:
if nums[index - 1] < target and nums[index] > target:
result = index - 1
break
elif nums[index] < target:
result = length
index += 1
return result