leetcode 35:Search Insert Position
来源:互联网 发布:jira7 linux安装 编辑:程序博客网 时间:2024/06/06 07:16
题目:
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);elsereturn binary(array, low, mid - 1, key);}};
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
- 二叉树中获取从根节点到某个节点的路径
- 蓝懿iOS 技术内容和心得 10。17
- Sql server语句(增删改查)
- Django开发教程 第二节 URL配置
- 怎样使用深度纹理
- leetcode 35:Search Insert Position
- play framwork Database 'default' needs evolution!
- Android Studio 使用日志:2.升级 JDK 后,Android Studio 启动编译报错的解决方法
- android 水果老虎机 文档一
- 写iOS SDK注意事项
- 密码学大作业系列~1
- 【Python】Learn Python the hard way, ex42 对、类及从属关系
- (C语言)搜狗的一道在线编程题
- 算法导论-选择数组中第K小的数(选择问题)