当前位置:网站首页>LeetCode->二分法(三)
LeetCode->二分法(三)
2022-07-26 23:17:00 【月半的人】
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left<right){
int middle = left+(right-left)/2;
if(nums[middle]>=target){
right = middle;
}else{
left = middle+1;
}
}
if(target>nums[nums.length-1]){
return nums.length;
}else{
return left;
}
}
}这道题就是不断用二分法逼近最靠近target的值,但是我们还需要注意的一点就是,当我们数组的最后一个值比target还要小的时候那么我们就需要返回nums.length->因为我们二分法是在0~nums.length进行寻找的.
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 0;
int right = arr.length-1;
while(left<right){
int middle = left+(right-left+1)/2;
if(arr[middle-1]<arr[middle]){
left = middle;
}else{
right = middle-1;
}
}
return left;
}
}这道题也是利用逼近的想法,不断找到逼近山峰,
但是注意middle= left+(right-left+1)/2;和left= middle->配套使用,防止出现死循环.
边栏推荐
- 见证中国网安力量 “解码2022中国网安强星”即将启航
- 【洋哥带你玩转线性表(四)——链式队列】
- How to judge whether a number is odd or even?
- C language - characters and strings, arithmetic operators, type conversions
- Go language slow start - package
- NAT网络地址转换协议-拓扑实验
- 通过ensp让静态路由实现全网可达
- 最新多线程&高并发学习资料,面试心里有底气
- Rip routing information protocol topology experiment
- [draw sherpinski triangle in C language]
猜你喜欢

Hcip OSPF comprehensive experiment

C language - assignment operator, compound assignment operator, self increasing and self decreasing operator, comma operator, conditional operator, goto statement, comment

见证中国网安力量 “解码2022中国网安强星”即将启航

【你了解Cache吗——全面理解高速缓冲存储器】

NAT network address translation protocol topology experiment

砺夏行动|源启数字化:既有模式,还是开源创新?

Record the nth SQL exception

Handsomeforum Learning Forum

C language - characters and strings, arithmetic operators, type conversions

What is the principle of synchronized lock escalation in multithreading?
随机推荐
uni-app上自定义微信小程序的tabbar
Find a specific number in an ordered array
Fist guessing applet based on Object-C novice on the road
The XML format of labelimg annotation is converted to yolov5
C language - value range of data type and basic data type
Hcip first day static routing comprehensive experiment
Redis五种基本数据结构
有趣的C语言
JVM interview questions (necessary for interview)
[brother Yang takes you to play with the linear table (III) - two way linked list]
HCIP oSPF综合实验
【在Visual Studio 2019中使用SQLite3库实现学生信息管理系统】
【用C语言绘制谢尔宾斯基三角形】
东北证券股票网上开户,手机上开户安全吗
HCIP第一天静态路由综合实验
Three handshakes and four disconnects of TCP
Constant knowledge explanation of C language
[C language programming] branch structure
Graduated and entered HW, from test engineer to project manager. Now I earn millions in goose factory every year. My suggestions to you
[brother Yang takes you to play with the linear table (I) - sequence table]