Search Insert Position插入位置

Easy, Binary Search

给定有序数列和一个目标值,返回目标值在数列中的位置。如果目标值不在序列中,返回插入位置。假设序列无重复值。

Examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

比较序列元素与目标值,返回逻辑比较反转的位置。

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """

        comp_results = [num < target for num in nums]
        return comp_results.index(False) if False in comp_results else len(nums)

你可能感兴趣的:(Search Insert Position插入位置)