Search inserted position Leetcode 35. By Python

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements in the array.

Example 1:

输入: [1,3,5,6], 5
输出: 2

Example 2:

输入: [1,3,5,6], 2
输出: 1

Example 3:

输入: [1,3,5,6], 7
输出: 4

Example 4:

输入: [1,3,5,6], 0
输出: 0

Thinking

  • The list is python index()method, if the target value in the array is very simple
  • If not, then on again from scratch, linear sweep, of course, better to find half position

Code

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        try:
            index_value = nums.index(target)
            return index_value
        except:
            length = len(nums)
            for i in range(length):
                if nums[i] > target and i > 0:
                    return i
                if nums[i] > target and i == 0:
                    return 0
                if nums[i] < target and i == length-1:
                    return length

# 二分法
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        length = len(nums)
        if length == 0:
            return 0
        left = 0
        right = length

        while left < right:
            mid = (left + right) // 2
            if nums[mid] < target:     # 此时已经排除mid位置是答案的可能性
                left = mid + 1
            else:
                right = mid
        return left  

Featured solution to a problem, there are taught dichotomy templates, said great, highly recommended


Stated

Source : stay button (LeetCode)
link: https://leetcode-cn.com/problems/search-insert-position

Guess you like

Origin www.cnblogs.com/MartinLwx/p/LeetcodeByPython.html