[leetcode]#35. Search Insert Position
来源:互联网 发布:页游多开软件 编辑:程序博客网 时间:2024/06/09 16:01
题意分析:
给定一个排好序的数组和一个target,如果target在数组里面,那么返回他的位置,否者返回他应该插入哪个位置。
题目思路:
这也是一个标准的二分查找。如果没有找到,那么和first和last位置的数比较一下就可以得到答案。
class Solution: # @param A, a list of integers # @param target, an integer to be inserted # @return integer def searchInsert(self, A, target): left = 0; right = len(A) - 1 while left <= right: mid = ( left + right ) / 2 if A[mid] < target: left = mid + 1 elif A[mid] > target: right = mid - 1 else: return mid return left
1 class Solution(object): 2 def searchInsert(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 first = 0;last = len(nums) - 1 9 while first < last:10 mid = (first + last + 1) // 211 if nums[mid] == target:12 return mid13 if nums[mid] < target:14 first = mid + 115 else:16 last = mid - 117 if nums[last] < target:18 return last + 119 if target <= nums[last]:20 return last21 if target < nums[first]:22 return first23 return first + 1
阅读全文
0 0
- [LeetCode]35.Search Insert Position
- LeetCode --- 35. Search Insert Position
- LeetCode 35.Search Insert Position
- [Leetcode] 35. Search Insert Position
- LeetCode 35. Search Insert Position
- [leetcode] 35.Search Insert Position
- Leetcode 35. Search Insert Position
- 35. Search Insert Position LeetCode
- [LeetCode]35. Search Insert Position
- LeetCode 35. Search Insert Position
- 【LeetCode】35. Search Insert Position
- leetcode 35. Search Insert Position
- leetcode 35. Search Insert Position
- LeetCode 35. Search Insert Position
- LeetCode *** 35. Search Insert Position
- leetcode 35. Search Insert Position
- [LeetCode]35. Search Insert Position
- LeetCode 35. Search Insert Position
- 穿上第一脚就会爱上~半个娱乐圈的女明星都在穿,今冬限量五折!丨钛空舱
- 工信部称运营商不得限制老用户选择套餐;“蓝翔技校”改为“蓝翔技院”;.欧委会计划再次起诉谷歌丨价值早报
- Mac下Git Commit时出错的一种解决方法
- 机器学习实战-13利用PCA来简化数据
- 代码中设置EditView的光标
- [leetcode]#35. Search Insert Position
- 在Android中使用SQLite的附加数据库(Attach DB)
- 树莓派挂载U盘
- Java Https请求工具类
- Numpy—np.random.seed()函数的应用
- android APP如何上线以及所做的哪些准备
- 小蓝单车解散迷局:高管分歧、退押金走后门、HR变卖家具
- Java中,&&与&,||与|的区别
- Servlet 中 session 的创建、销毁及监听 原创 2016年03月23日 18:09:33 标签:session /session超时 /在线人数统计 4916 1、session 和 c