LeetCode35:https://leetcode-cn.com/problems/search-insert-position/
解题思路:一种比较笨的方法,直接比较
1 class Solution: 2 def searchInsert(self, nums: List[int], target: int) -> int: 3 if target in nums: 4 for i in range(len(nums)): 5 if nums[i] == target: 6 return i 7 else: 8 if max(nums) < target: 9 return len(nums) 10 for s in range(len(nums)): 11 if nums[s] > target: 12 return s
看了题解:只要在数组中找到比目标元素要大的元素即可。如果没有找到,即说明目标元素是最大的。
1 class Solution: 2 def searchInsert(self, nums: List[int], target: int) -> int: 3 for i in range(len(nums)): 4 if nums[i] >= target: 5 return i 6 return len(nums)
原文:https://www.cnblogs.com/vvzhang/p/14413091.html