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:
給一個有序的數(shù)組和一個目標值,返回這個目標值在數(shù)組里的位置索引涯呻。如果找不到熔脂,請返回目標值如果在這個有序數(shù)列中的索引眉睹。
這個數(shù)組里沒有重復的元素。
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:
這道題主要運用的是折半查找的方法灼芭,屬于最基本的數(shù)據(jù)結構知識有额。