当前位置:网站首页>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;}} 边栏推荐
猜你喜欢
随机推荐
免费文档翻译-免费批量文档翻译软件推荐
SQL函数 TRIM
Idea 全局搜索(idea如何全局搜索关键字)
匹配滤波(四种滤波器的幅频特性)
Excel dynamic chart production
19、商品微服务-srv层实现
JSP中include指令的功能简介说明
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
暑期总结3
darknet训练yolov4模型
jvmxmx和xms参数分析(设定优化校准)
Jest 测试框架 beforeEach 的设计原理解析
今日睡眠质量记录85分
SQL(面试实战07)
如何在 UE4 中制作一扇自动开启的大门
半夜赶工制作简报的我好想说 : 确定了,最终稿就是这样
【云驻共创】数据工坊平台,0代码开发数据处理业务“快”人一步
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
中原银行实时风控体系建设实践
项目监控六大事项









