当前位置:网站首页>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;}} 边栏推荐
- 如何通过DBeaver 连接 TDengine?
- 19、商品微服务-srv层实现
- 运行yum报错Error: Cannot retrieve metalink for reposit
- 数字化转型中的低代码
- LeetCode笔记:Weekly Contest 304
- 学习经验分享之七:YOLOv5代码中文注释
- npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
- Mysql transaction isolation level and MVCC (multi-version concurrency control)
- [kali-information collection] (1.9) Metasploit + search engine tool Shodan
- 解决导出excel文件名中文乱码的问题
猜你喜欢
随机推荐
细学常用类,集合类,IO流
doc2vec和word2vec(zigbee简介及应用)
Breaking the Boundary, Huawei's Storage Journey
jvmxmx和xms参数分析(设定优化校准)
如何在 UE4 中制作一扇自动开启的大门
JSP中include指令的功能简介说明
运行yum报错Error: Cannot retrieve metalink for reposit
数字化转型中的低代码
QT笔记——Q_PROPERTY了解
Excel dynamic chart production
leetcode: 200. Number of islands
基于深度学习的裂缝检测技术
雷克萨斯,锁死的安全,挡不住的心寒
【Acunetix-Forgot your password】
学习经验分享之七:YOLOv5代码中文注释
华为eNSP(基础实验通信)
如何通过DBeaver 连接 TDengine?
暑期总结3
npm install报错npm ERR Could not resolve dependency npm ERR peer
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?









