[leetcode] 35. Search Insert Position 解题报告
2016-01-02 11:34
316 查看
题目链接:https://leetcode.com/problems/search-insert-position/
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.
思路:一个简单的二分查找,没什么好说的
代码如下:
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
思路:一个简单的二分查找,没什么好说的
代码如下:
class Solution { public: int searchInsert(vector<int>& nums, int target) { int left = 0, right = nums.size()-1; while(left <= right) { int mid = (left+right)/2; if(nums[mid] < target) left = mid+1; else right = mid-1; } return left; } };
相关文章推荐
- 1.2 ASSEMBLY LANGUAGE
- mysql 简单练习
- 四则运算 Day3
- 客户端到服务器端的通信过程及原理
- JavaScript中--- undefined与null的区别 及===与== 数据比较
- 中文分词算法基础
- ABP理论学习之授权(Authorization)
- 抓包工具Fidder详解(主要来抓取Android中app的请求)
- 获取itkImage的大小
- ArcGIS应用分析--学校选址
- 使用Xcode DEBUG模式和RELEASE模式 ... 宏定义实现注释功能
- 【英语】December
- 学习总结(css)
- 彩云国物语片头曲_はじまりの風
- POJ 2528 Mayor's posters(线段树区间修改+离散化)
- 模板错误总结
- K均值聚类的失效性分析
- K均值聚类的失效性分析
- for
- 数据结构_2:链表:C++