当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
excel 批量翻译-excel 批量函数公司翻译大全免费
[email protected] This version of tar is no longer supported, and will not receive"/>
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
使用mosquitto过程中的问题解决
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
Shell编程案例
Swift中什么时候不能用 () 代替 Void 来使用
“纯C”实现——三子棋小游戏
QListView的使用
JVM简介
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
随机推荐
匹配滤波(四种滤波器的幅频特性)
pyqt5连接MYSQL数据库问题
SQL(面试实战07)
npm install报错npm ERR Could not resolve dependency npm ERR peer
go源码之sync.Waitgroup
ABAP-OOAVL模板程序
学习经验分享之七:YOLOv5代码中文注释
阿苹的思考
go语言的接口
darknet训练yolov4模型
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
SQL 数据更新
Shell编程之条件语句
看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
Several reasons why applet plugins benefit developers
Oracle 19c配置ob server
How to technically ensure the quality of LED display?
网站自动翻译-网站批量自动翻译-网站免费翻译导出
暑期总结3
Oracle 19c 连接PDB