LintCode 60 搜索插入位置
来源:互联网 发布:亚马逊调价软件 编辑:程序博客网 时间:2024/05/12 04:38
题目:searchInsert
要求:
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例:
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
算法要求:
O(log(n)) time
解题思路:
就是二分查找- -直接上去噜噜噜噜~
算法如下:
int searchInsert(vector<int> &A, int target) { // write your code here int left = 0; int right = A.size() - 1; int mid = (right + left) / 2; if (A.size() != 0 && *A.begin() > target) { A.insert(A.begin(), target); return 0; } while (left <= right) { if (A[mid] == target) { return mid; } else if (A[mid] > target) { right = mid - 1; mid = (right + left) / 2; } else { left = mid + 1; mid = (right + left) / 2; } } A.insert(A.begin() + left, target); return left; }
0 0
- LintCode 60 搜索插入位置
- LintCode : 搜索插入位置
- lintcode ----搜索插入位置
- LintCode : 插入搜索位置
- Lintcode 搜索插入位置
- lintcode:搜索插入位置
- Lintcode搜索插入位置
- lintCode 搜索插入位置
- 【lintcode笔记】搜索插入位置
- 【LintCode】Search Insert Position 搜索插入位置
- lintcode python 容易 60.搜索插入位置
- lintcode&九章算法——No.60 搜索插入位置 ? 待解决
- LintCode 二分法查找, 搜索插入位置 和 二维矩阵
- 题目:搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 搜索插入位置
- 规则引擎Drools
- 愚蠢的问题关于struct和typedef struct
- Java文件流应用:剪切文件
- android studio快捷鍵
- wordpress配置点滴
- LintCode 60 搜索插入位置
- 贪吃蛇智能版(中级)
- Python3 面向对象
- java中Port端口是怎么回事?有什么用?
- getContextPath、getServletPath、getRequestURI的区别
- 2016年最新云计算视频教程hadoop大数据实战开发
- 进阶递归之2的幂次方表示
- ACM_HDU 2033 人见人爱A+B
- java中localhost是怎么回事?干什么用的?