7.2—查找—Sear 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.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
#include<iostream>
using namespace std;
bool found = false;
int SearchInsertPosition(int a[], int n, int k)
{int index = -1;if (n <= 0)return index;int begin = 0;int end = n - 1;int mid;while (begin <= end){mid = (begin + end) / 2;if (a[mid] < k)begin = mid + 1;else if (a[mid] > k)end = mid - 1;else{index = mid;found = true;return index;}}//=====return begin;// end + 1;
}
int main()
{const int n = 4;int a[n] = { 1, 3, 5, 6 };int targt = 5;int index = SearchInsertPosition(a, n, targt);if (found)cout << "Found!" << " " << index << endl;elsecout << "Not Found! Insert" << " " << index << endl;
}
7.2—查找—Sear Insert Position相关推荐
- LeetCode - 35. Search Insert Position
35. Search Insert Position Problem's Link ---------------------------------------------------------- ...
- LeetCode算法入门- Search Insert Position -day19
LeetCode算法入门- Search Insert Position -day19 题目描述 Given a sorted array and a target value, return the ...
- leetcode -- Search Insert Position
2019独角兽企业重金招聘Python工程师标准>>> Search Insert Position Given a sorted array and a target value, ...
- 【二分法】LeetCode 35. Search Insert Position
LeetCode 35. Search Insert Position Solution1:我的答案 class Solution { public:int searchInsert(vector&l ...
- 【LeetCode】- Search Insert Position(查找插入的位置)
[ 问题: ] Given a sorted array and a target value, return the index if the target is found. If not, re ...
- LeetCode Search Insert Position (二分查找)
题意: 给一个升序的数组,如果target在里面存在了,返回其下标,若不存在,返回其插入后的下标. 思路: 来一个简单的二分查找就行了,注意边界. 1 class Solution { 2 publi ...
- [LeetCode] Serch Insert Position (总结二分查找) Java version
原题地址:https://oj.leetcode.com/problems/search-insert-position/: 查找插入口,在使用二分查找发的时候需要注意,与以前不同.在没有找到与tar ...
- 二分法:search insert position 插入位置
问题描述: 给定一个排序数组nums(无重复元素)与目标值target,如果target在nums里 出现,则返回target所在下标,如果target在nums里未出现,则返回target应该 插入 ...
- Leetcode:Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the ...
最新文章
- 【抬杠】在某些时候不希望用户缩小浏览器的宽度,因为咳咳~会导致你的布局混乱,那么这个代码就是帮助你如何限制浏览器宽度的
- C/C++连接MySql数据库
- win2003 https 网站的图文配置教程
- JAVA运算符\操作符
- React中 useState在合成事件中是异步的,怎么获取到useState 设置后的最新值,或者说setState中获取到最新值
- CF650E-Clockwork Bomb【并查集】
- html css js速成_CSS速成课程
- python api加快交易速度_使用Python3的pipedriveapi将交易输出限制为1000个交易
- matlab里的copula函数,常见copula函数简介
- 如何用pe安装服务器系统安装系统教程视频,微pe安装系统教程视频
- SpringBoot项目整合JasperReport报表生成PDF并下载
- linux大于16T硬盘分区,linux硬盘超过16分区
- 水木周平:就业难?招人更难!
- torch.nn到底是什么?
- C++ 3D 绘图技术调研常用库介绍
- 国内jQuery CDN
- 无线传感器网络中的节点定位技术
- 为什么PRD写的Low?你看图文、支付、数据、登录、按钮……藏了多少猫腻!(文末送44页淘宝PRD)...
- 7、魔兽世界一种私服搭建服务器mangosZero答疑
- 亿流量大考(4):自研ES+HBase+纯内存的高性能毫秒级查询引擎