LeetCode 35:Search Insert Position
2016-02-03 23:21
453 查看
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.
给定一个已排序数组和目标值,返回目标值在数组中的下表。如果没有在数组中找到,返回目标值在插入排序下应该插入的位置。
这里有一些示例:
5 → 2
2 → 1
7 → 4
0 → 0
事先说明下,进入medium后许多题目开始和算法相关,而本人的算法属于一般 需要重学 的情况。因此可能两三天做出来一道题也说不定,也有很多情况下会去研究discuss里别人的实现方法。唯一能够保证的就是所有代码均为本人亲手敲出来并AC后再放到这个
基本没人看的 博客里面。
我自己的想法挺简单,就是遍历一遍找到该插入的地方完事。。。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++)
{
if(target<=nums[i])
return i;
}
return nums.size();
}
};
AC后我随手点开来看了看,提示我beats了4.2%的人。。。于是我感觉这样不行啊,得想个更好的办法。后来发现给定数组是排好序的,那么如果用二分查找,算法复杂度不就只有O(lnn)了么!然而,问题只有一个:我
不会写 不熟悉二分查找。。。
只好从discuss里面随便找了个代码,二分查找应该还是挺简单的我就不解释了
class Solution
{
public:
int searchInsert(vector<int>& nums, int target)
{
int lo = 0, hi = nums.size(), mid;
// find index whose value first is greater than target
while(lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] > target) hi = mid;
else lo = mid + 1;
}
// find the target?
if (lo > 0 && nums[lo - 1] == target) --lo;
return lo;
}
};
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
给定一个已排序数组和目标值,返回目标值在数组中的下表。如果没有在数组中找到,返回目标值在插入排序下应该插入的位置。
这里有一些示例:
[1,3,5,6],
5 → 2
[1,3,5,6],
2 → 1
[1,3,5,6],
7 → 4
[1,3,5,6],
0 → 0
事先说明下,进入medium后许多题目开始和算法相关,而本人的算法属于一般 需要重学 的情况。因此可能两三天做出来一道题也说不定,也有很多情况下会去研究discuss里别人的实现方法。唯一能够保证的就是所有代码均为本人亲手敲出来并AC后再放到这个
基本没人看的 博客里面。
我自己的想法挺简单,就是遍历一遍找到该插入的地方完事。。。
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++)
{
if(target<=nums[i])
return i;
}
return nums.size();
}
};
AC后我随手点开来看了看,提示我beats了4.2%的人。。。于是我感觉这样不行啊,得想个更好的办法。后来发现给定数组是排好序的,那么如果用二分查找,算法复杂度不就只有O(lnn)了么!然而,问题只有一个:我
不会写 不熟悉二分查找。。。
只好从discuss里面随便找了个代码,二分查找应该还是挺简单的我就不解释了
class Solution
{
public:
int searchInsert(vector<int>& nums, int target)
{
int lo = 0, hi = nums.size(), mid;
// find index whose value first is greater than target
while(lo < hi)
{
mid = (lo + hi) / 2;
if (nums[mid] > target) hi = mid;
else lo = mid + 1;
}
// find the target?
if (lo > 0 && nums[lo - 1] == target) --lo;
return lo;
}
};
相关文章推荐
- 利用java来访问网站
- 处理job abend基本流程
- java排序中用到的两种比较方式:Comparable,Comparator
- c++特性:Lambda表达式
- 关于“final实例域”
- [转载]oracle物化视图
- 【DP+斜率优化】[HNOI2008][HYSBZ/BZOJ1010]玩具装箱toy
- 六种值得学习的android开发框架
- shell之路【第四篇】输入输出重定向
- 使用stl for_each的三种方法
- mysql按年度、季度、月度、周、日统计查询的sql语句
- MySQL 时间和日期函数
- oracle物化视图
- POJ 2096 Collecting Bugs(概率DP)
- Python实现DBScan
- keepalived+LVS 实现双机热备、负载均衡、失效转移 高性能 高可用 高伸缩性 服务器集群
- leetcode之Best Time to Buy and Sell Stock II
- [转载]oracle位图索引
- UITableView练习二之Dynamic Prototypes练习
- 智慧北京开发第一天(上)