LeetCode 题 - 35. 搜索插入位置
2019-03-31 13:39
543 查看
搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5 输出: 2
示例 2:
输入: [1,3,5,6], 2 输出: 1
示例 3:
输入: [1,3,5,6], 7 输出: 4
示例 4:
输入: [1,3,5,6], 0 输出: 0
python解答代码:
def searchInsert(nums: List[int], target: int) -> int: if target in nums: return nums.index(target) nums.append(target) nums.sort() return nums.index(target)
另一种方法:
def searchInsert(nums: List[int], target: int) -> int: for x, num in enumerate(nums): if target <= num: return x return len(nums)
二分法:
def searchInsert(nums: List[int], target: int) -> int: """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) while low < high: mid = low + (high - low)//2 if nums[mid] > target: high = mid elif nums[mid] < target: low = mid +1 else: return mid return low
相关文章推荐
- LeetCode 35. 搜索插入位置 Python
- Leetcode35. 搜索插入位置(python3)
- LeetCode35. 搜索插入位置(java)
- leetcode35.搜索插入位置
- LeetCode35. 搜索插入位置
- leetcode 35. Search Insert Position搜索插入位置(二分查找)
- LeetCode 35. 搜索插入位置
- Leetcode 35. 搜索插入位置
- leetcode之数组类之数组的旋转与分治类-----OJ 189/33/81/153/154 数组旋转 旋转数组搜索 88 有序数组合并 4 两个有序数组寻找第K个元素/中位数 35 寻找插入位置
- LeetCode 35. Search Insert Position(查找插入位置)
- leetcode 35 Search Insert Position.(搜索元素插入数组的位置)
- (LeetCode每日一刷11)搜索插入位置
- 【LeetCode-面试算法经典-Java实现】【035-Search Insert Position(搜索插入位置)】
- Leetcode 35_搜索插入位置 --python
- leetcode的python实现 刷题笔记35:搜索插入位置的暴力解法和优化解法
- LeetCode第35题:搜索插入位置
- LeetCode:第35题:搜索插入位置(search-insert-position)
- 【LeetCode】[35] 搜索插入位置
- 【LeetCode】Search Insert Position搜索插入位置[数组、二分法] - Medium
- Leetcode(35) 搜索插入位置