当前位置:网站首页>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;}} 边栏推荐
猜你喜欢
随机推荐
翁恺C语言程序设计网课笔记合集
今日睡眠质量记录85分
CAN总线的AUTOSAR网络管理
Crack detection technology based on deep learning
Several reasons why applet plugins benefit developers
服务器间传输文件
当POC遇见RPA:RPA项目顺利实施的关键
Oracle 19c 连接PDB
面积曲线AUC(area under curve)
智能手表前景如何?
C#为listview选中的项添加右键菜单
SQL(面试实战07)
openresty 性能优化
yolo格式(txt)数据集转VOC(xml)
企业级数据治理工作怎么开展?Datahub这样做
流动性质押挖矿系统开发如何制作?单双币系统开发成熟技术
字母交换--字符串dp
Learning Experience Sharing Seven: YOLOv5 Code Chinese Comments
SQL函数 TRIM
LeetCode笔记:Weekly Contest 304









