leetcode35 python implements search for insertion position

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.

You can assume that there are no duplicate elements in the array.

Example 1:

Input: [1,3,5,6], 5
 Output: 2

Example 2:

Input: [1,3,5,6], 2
 Output: 1

Example 3:

Input: [1,3,5,6], 7
 Output: 4

Example 4:

Input: [1,3,5,6], 0
 Output: 0
python language
class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        length=len(nums)
        if nums[0]>target:
            return 0# first insert
        if nums[-1]<target:
            return length#The last insert
        for i in range(length):
            if nums[i]==target:
                return i
            if target not in nums:#When target is not in nums
                if target>nums[i] and target<nums[i+1]:
                    return i+1
        



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325675620&siteId=291194637