当前位置:网站首页>Likou 35 - search for insertion position - binary search
Likou 35 - search for insertion position - binary search
2022-08-02 11:45:00 【Zhang Dui Dui)】
Title description
Given a sorted array and a target value, find the target value in the array and return its index.If the target value does not exist in the array, returns the position where it will be inserted in order.
Please use an O(log n) algorithm.
Solution ideas
- This is also a question of finding elements, the title requirement is to find elements in an ordered array and return the index;
- If the element is not in the array, it should return its index position;

- Then the target value may have four cases: ① It is smaller than the first element and placed at the front of the array; ② It is larger than the last element and inserted at the end of the array; ③ It is equal to a value in the array, and returnsIndex; ④ The value is not found in the array, find a suitable position to insert it
- It is conceivable that this kind of problem should be solved by the dichotomy method;
- At the beginning, judge the size relationship between target and the first and last elements of the array, and return the correct index;
- Use the left and right closed interval [ left , right ] in the search process;
- Just after judging all the cases, it should not return -1, it should return right+1, because right+1 is the index of the position to be inserted at this time.
Input and output example

Code
class Solution {public int searchInsert(int[] nums, int target) {int n = nums.length;int left = 0, right = n-1;//boolean flag = false;if(target < nums[0]){return 0;}else if(target > nums[n-1]){return n;}while(left <= right){int mid = left + ((right - left) >> 1);if(target == nums[mid]){//flag = true;return mid;}else if(target nums[mid]){//flag = true;left = mid + 1;}}return right+1;}} 边栏推荐
- 【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
- The sitcom "Re-Walking the Long March" was staged
- 【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
- Shell编程案例
- LeetCode笔记:Weekly Contest 304
- 【Acunetix-忘记密码】
- 企业级数据治理工作怎么开展?Datahub这样做
- Swift中什么时候不能用 () 代替 Void 来使用
- openresty 性能优化
- 10份重磅报告 — 展望中国数字经济未来
猜你喜欢

Crack detection technology based on deep learning

npm run dev 和 npm run serve区别

sva 断言资料

Axure谷歌浏览器扩展程序下载及安装方法(免翻墙)

CCF paper conference IEEE how to query all articles of a conference journal

细学常用类,集合类,IO流

Getting Started with Three.JS Programmatic Modeling

Camera Hal OEM模块 ---- cmr_snapshot.c

Hub and Spoke配置案例

The exchange - string dp
随机推荐
8大软件供应链攻击事件概述
npm run dev 和 npm run serve区别
OSI 七层模型和TCP/IP模型及对应协议(详解)
面积曲线AUC(area under curve)
SQL function $TRANSLATE
ansible module --copy module
SQL函数 TRIM
go语言的接口
智能手表前景如何?
如何通过DBeaver 连接 TDengine?
Excel dynamic chart production
Excel动态图制作
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
SQL function TRIM
喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
图形处理单元(GPU)的演进
小程序插件的生态丰富,加速开发建设效率
Shell编程之条件语句
MP的几种查询方式