继续把知乎发的挪到这里https://zhuanlan.zhihu.com/p/38404527
题目:
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.
Examples :
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:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for idx, val in enumerate(nums):
diff = target-val
# same value with target
if diff == 0:
return idx
# biger than target
elif diff < 0:
return idx
return len(nums)
本文介绍了一种在已排序且无重复元素的数组中查找指定目标值插入位置的方法。通过遍历数组并比较目标值与数组元素之间的差异,确定目标值应该插入的位置。该算法适用于各种基于数组的操作。
436

被折叠的 条评论
为什么被折叠?



