【leetcode刷提笔记】Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0


 

题解:简单的二分搜索,直接放代码:

JAVA版本:

复制代码
 1 public int searchInsert(int[] A, int target) {
 2         int answer = 0;
 3         int front = 0;
 4         int end = A.length-1;
 5         while(front <= end){
 6             int mid = (front + end)/2;
 7             if(A[mid] == target)
 8                 return mid;
 9             if(A[mid] < target)
10                 front = mid + 1;
11             else 
12                 end = mid-1;
13         }
14         return front;
15     }
复制代码

 

posted @   SunshineAtNoon  阅读(167)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2014-03-31 【leetnode刷题笔记】Maximum Depth of binary tree
2014-03-31 【leetcode刷题笔记】Single Number
点击右上角即可分享
微信分享提示