Description:
Given a sorted array 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 may assume no duplicates in the array.
Translate:
給一個有序的數組和一個目標值,返回這個目標值在數組里的位置索引。如果找不到,請返回目標值如果在這個有序數列中的索引。
這個數組里沒有重復的元素。
Example:
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
Solution:
def searchInsert(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) / 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return low
by https://leetcode.com/problems/search-insert-position/discuss/15081
Analysis:
這道題主要運用的是折半查找的方法,屬于最基本的數據結構知識。