35.leetcode 搜索插入位置(简单)

leetcode python 刷题记录,从易到难

一、题目

在这里插入图片描述

二、解答

1.思路

分三种情况

  • 插入位置在开头,直接返回0即可
  • 插入位置在中间,遍历数组,如果当前元素等于插入元素,则返回当前元素的索引。如果当前元素大于插入元素,则返回当前元素的索引
  • 遍历完元素后,发现插入元素在目标数组中不存在,此时数组长度所在的索引就是目标索引

2.实现

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        if nums[0] > target:
            return 0
        for i in range(0,len(nums)):
            if target==nums[i]:
                return i
            elif target<nums[i]:
                return i
        else:
            return len(nums)

3.提交

在这里插入图片描述

4.Github

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/35.py

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/108309443