leetcode035-python 搜索插入位置

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.

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

解题要点:

1.列表的寻找功能index函数,判断元素是否在列表中a in list。

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        ans = 0
        n = len(nums)
        if target in nums:
            ans = nums.index(target)
            return ans
        else:
            for i in nums:
                if i < target:
                    ans += 1
                else:
                    break
            return ans

引用\[1\]中给出了一段Java代码,是关于LeetCode 114题的解法。这道题的要求是将二叉树展开为一个单链表。引用\[2\]中提到了这道题可以用递归解法,而不一定要求空间复杂度为O(1)。引用\[3\]中给出了一种解题思路,即将左子树插入到右子树的地方,然后将原来的右子树接到左子树的最右边节点,最后重复这个过程直到新的右子树为null。 根据以上引用内容,可以使用递归的方式来解决LeetCode 114题。具体的Python代码如下: ```python class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return self.flatten(root.left) self.flatten(root.right) if root.left: temp = root.right root.right = root.left root.left = None while root.right: root = root.right root.right = temp ``` 这段代码首先判断根节点是否为空,如果为空则直接返回。然后递归地对左子树和右子树进行展开。如果根节点的左子树不为空,将右子树保存到临时变量temp中,然后将左子树赋值给右子树,左子树置为空。接着,找到新的右子树的最右边节点,将temp连接到该节点的右侧。 这样,通过递归的方式,就可以将二叉树展开为一个单链表。 #### 引用[.reference_title] - *1* *2* *3* [【LeetCode 114】二叉树展开为链表(Python)](https://blog.csdn.net/Lucy_R/article/details/107827298)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值