leetcode_c++:Search insert position(035)
2016-05-18 01:09
423 查看
题目
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
算法
stl的lower_bound复杂度
o(lgN)#include<iostream> #include<vector> #include <algorithm> using namespace std; class Solution { public: int searchInsert(vector<int>& nums, int target) { int l=0,r=nums.size()-1,mid=0; while(l<r){ mid=l+(r-l)/2; if(nums[mid]<target) l=mid+1; else r=mid; } return nums[l]<target ? l+1:l; } };
相关文章推荐
- 【C语言】迷宫游戏设计思路与功能体会及简单的改进报告
- leetcode_c++:Search for a Range(034)
- 【C语言】C语言32个关键字简介和9种控制语句
- C++ STL实例(一)
- C++ STL-string实例
- 模拟图书管理系统(简单c语言DOS界面)
- C++11: Multi-Thread思考.
- C++ Variadic template(可变长度参数函数)
- 八种排序算法之-c实现
- c语言学习笔记9之switch语句
- C语言指针 和 学生宿舍管理系统
- C语言中预定义符 __FILE__, __LINE__, __FUNCTION__, __DATE__, __TIME__ 的使用
- C语言中的静态变量和普通变量的区别
- C++面向对象实验(五)
- C语言的指针、链表的原理和各类操作
- 2016/5/17 初识C++
- leetcode_c++:Search in Rotated Sorted Array(033)
- C++中getline函数用法(修正调试ok)
- 拓扑序列 C++实现
- 2013蓝桥决赛C/C++B组