leetcode-35-search insert position
来源:互联网 发布:排课软件价格 编辑:程序博客网 时间:2024/06/06 04:43
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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
大意:在有序数组中插入元素。
思路:二分查找,找到target就返回此刻索引。否则维护和target距离最小的那个索引。最后判断该位置元素和target大小比较。
python一遍AC。
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ l,r=0,len(nums)-1 ans=0 dismin=9999 if r==-1:return 0 while(l<=r): m=(l+r)/2 if nums[m]==target: return m if nums[m]<target: dis=abs(nums[m]-target) if dis<dismin: dismin=dis a=m l=m+1 else: dis=abs(nums[m]-target) if dis<dismin: dismin=dis a=m r=m-1 if nums[a]<target: return a+1 else: return a
再一考虑,发现不需要维护dismin。直接二分查找。最后返回l and r。
找到了返回m,找不到返回left即可。
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ l,r=0,len(nums)-1 ans=0 dismin=9999 if r==-1:return 0 while(l<=r): m=(l+r)/2 if nums[m]==target: return m if nums[m]<target: l=m+1 else: r=m-1 return l
c++:
class Solution {public: int searchInsert(vector<int>& nums, int target) { int n = nums.size(); int low = 0; int high = n -1; int mid; while(low <= high) { mid = low + (high - low)/2; if(target == nums[mid]) return mid; else if(target < nums[mid]) high = mid - 1; else low = mid + 1; } return low; } };
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
- 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
- Leetcode#35||Search Insert Position
- 顺序表应用2:多余元素删除之建表算法
- 全局变量、局部变量、静态全局变量、静态局部变量
- [数据结构]哨兵作用
- redis cluster集群配置
- Datapump 之impdp/expdp简单使用总结
- leetcode-35-search insert position
- javascript 时间倒计时
- 基于物品的协同过滤-itemBase
- Linux中vim 复制与粘贴
- discuz论坛首页默认显示单个特定的版块,及自定义论坛首页固定标题
- 概念名词解释&读写(一)
- 母函数入门 专题
- HDU 4737 A Bit Fun 水暴力
- C++课设