leetcode 35:Search Insert Position
2015-10-17 22:08
489 查看
题目:
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,即
if(low>high) return -1;
现在返回的就是low或者是high了,也是比较简单,时间复杂度:O(lgn)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int size = nums.size();
if (size == 0) return 0;
return binary(nums, 0, size - 1, target);
}
int binary(vector<int>&array, int low, int high, int key)
{
if (low > high)
{
return low;
}
int mid = (low + high) / 2;
if (array[mid] == key)
return mid;
else if (array[mid] < key)
return binary(array, mid + 1, high, key);
else
return binary(array, low, mid - 1, key);
}
};
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
思路:
其实像这种只要是排好序的查找,基本思路都是在二分法查找基础上做变化。本题也是这样,不过以前没找到的话,返回-1,即
if(low>high) return -1;
现在返回的就是low或者是high了,也是比较简单,时间复杂度:O(lgn)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int size = nums.size();
if (size == 0) return 0;
return binary(nums, 0, size - 1, target);
}
int binary(vector<int>&array, int low, int high, int key)
{
if (low > high)
{
return low;
}
int mid = (low + high) / 2;
if (array[mid] == key)
return mid;
else if (array[mid] < key)
return binary(array, mid + 1, high, key);
else
return binary(array, low, mid - 1, key);
}
};
相关文章推荐
- python_2(编译,变量、引号、变量类型、算数表达式)
- java访问者模式
- 一款简单易用的 DNS 发包工具
- 13个MySQL数据库的实用SQL小技巧
- 基于Theano的深度学习(Deep Learning)框架Keras学习随笔-06-激活函数
- shell学习-转自http://c.biancheng.net/cpp/shell/
- VIm有以下几个模式
- BestCoder Round #60 1002
- JVM里面hashtable和hashmap实现原理
- java中URLEncode和URLDecode
- 代码复查的内容与方法
- java状态模式
- 2015/10/17偶得
- Juint4源码解读
- 随心一爬
- JDK高性能编程之多线程
- iOS设计模式 - 命令
- android 34 ListView进阶
- CSS控制链接
- Java基础----Java容器之集合