Leetcode-Search Insert Position-Python
来源:互联网 发布:c语言中bind函数 编辑:程序博客网 时间:2024/06/15 14:52
Search Insert Position
给定一个有序的无重复元素的序列,和一个目标元素,求出该元素在数组中的下标,若数组中不存在该元素,则返回其在数组中的顺序下标。
Description
解题思路:
直接采用暴力查询。首先判断目标元素是否在数组中,若存在,则直接返回下标。
若不存在,将目标元素与数组中的最大最小值比较;如果介于最大最小值之间,则与数组中的任意两个相邻元素进行比较。
def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target in nums: return nums.index(target) if target<min(nums): return 0 elif target>max(nums): return len(nums) else: for i in range(len(nums)): if nums[i]<target and nums[i+1]>target: return i+1
改进:
采用二分查找的思路,leetcode上提供的另一种解法。
def searchInsert(self, nums, key): if key > nums[len(nums) - 1]: return len(nums) if key < nums[0]: return 0 l, r = 0, len(nums) - 1 while l <= r: m = (l + r)/2 if nums[m] > key: r = m - 1 if r >= 0: if nums[r] < key: return r + 1 else: return 0 elif nums[m] < key: l = m + 1 if l < len(nums): if nums[l] > key: return l else: return len(nums) else: return m
阅读全文
0 0
- Leetcode-Search Insert Position-Python
- 【Leetcode】【python】Search Insert Position
- 【LeetCode with Python】 Search Insert Position
- [leetcode:python]35.Search Insert Position
- 【LeetCode 35】Search Insert Position(Python)
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode-Search Insert Position
- LeetCode - Search Insert Position
- LeetCode | Search Insert Position
- Leetcode: Search Insert Position
- 【LeetCode】Search Insert Position
- cf Educational Codeforces Round 26 E. Vasya's Function
- 算法学习之旅,初级篇(9)--字符串逆序
- java多线程初探
- java的基础语法(个人总结)
- sublime软件设置整理
- Leetcode-Search Insert Position-Python
- 上层使用jni(从java层到framework到JNI的用法过程)
- ural1846 GCD2010(线段树+gcd+离散化)
- Spring MVC 中图片等静态资源无法加载
- JavaScript数组排序
- HBase伪分布式的搭建
- android arm64硬件实现加速crc32算法
- GPU概念的一点总结
- javaScript:函数