当前位置:网站首页>Sword finger offer 53 - I. find the number I in the sorted array
Sword finger offer 53 - I. find the number I in the sorted array
2022-07-19 02:36:00 【jjj34】
Title Description

Ideas : find target-1 The rightmost sum of target The rightmost number , Two less is good
The code is as follows :
class Solution {
public int search(int[] nums, int target) {
// Find the rightmost number , Subtraction of two numbers
//target-1 The rightmost number ,target The rightmost number
return binarysearch(nums,target)-binarysearch(nums,target-1);
}
public int binarysearch(int[] nums,int target)
{
int left=0;
int right=nums.length;
while(left<right)
{
int mid=left+(right-left)/2;//right=n Guaranteed binary sum left<right
if(nums[mid]>target)
{
right=mid;
}
else//<= All to the left
{
left=mid+1;
}
}
return left;
}
}Possible doubts
1. How to ensure to find the rightmost number ?
while(left < right)
------------------------
else//<= All to the left
{
left=mid+1;
}
These two paragraphs realize finding the rightmost number
give an example : When the result is [4,5] , The goal is 4 when ,
left = 4
right = 5
mid = 4
According to judgment ,left = mid +1;
here ,left == right Out of the loop
left-1 perhaps right-1 Namely target The rightmost number of To find the rightmost number
2.right = nums.length instead of nums.length-1
1. because nums[right] There was no access to
2. To ensure the mid Half every time
int mid=left+(right-left)/2
3.mid = left +(right-left) /2 instead of mid = (left+right)/2
When left and right When I was younger , Both cases are ok
But one situation is left and right They're all bigger , here ,left + right Will cause removal , So subtraction is better
边栏推荐
- D - Parity game离散化+带权并查集
- UE4 笔记
- [hdrp HD rendering pipeline] create hdrp project and upgrade the built-in pipeline project to hdrp project
- 性能之流量回放
- [unity panel attribute literacy] set texture import settings after importing textures
- 3D NFT的破茧重生:Caduceus去中心化边缘渲染技术
- 【瑞吉外卖⑩】Linux 粗略学习 & Redis 粗略学习
- sqlmap的使用
- 仅以此篇纪念负数取模
- If a hunter shoots a rabbit with a gun
猜你喜欢
随机推荐
jmeter连接数据库的方法
status 500 reading AftersaleService#getAftersaleList(Long)+com.sun.proxy.$Proxy214.getAftersaleList
逆元(名字太多人用我就加这几个字)
How to configure multiple SSH keys for novices (easy to understand hand-in-hand teaching)
静态路由(详)
新手如何配置多个 SSH Key(通俗易懂手把手教学)
[unity Editor Extension] unity makes its own exclusive editor panel
php伪协议实现命令执行
转载:SQL注入常见绕过
Tree array and St table
Detailed explanation of caduceus project of metauniverse public chain (I): project concept and technical framework of caduceus metaverse protocol
Bugku problem solution
Bugku---- regular matching, cookies
BeanShell脚本获取当前时间
Make a simple record and check the set
网络层协议和IP数据包的格式(详解)
【已解决】参考了本地mysql忘记密码后, [Server] --initialize specified but the data directory has files in it. Aborti
【Unity编辑器扩展】快速定位资源和脚本的指定文件和路径
剑指 Offer 53 - I. 在排序数组中查找数字 I
如果猎人用枪打兔子









