当前位置:网站首页>leetcode 704·二分查找
leetcode 704·二分查找
2022-04-21 06:37:00 【小学五年级在读的蒟蒻】
leetcode 704·二分查找
大家好,我是小学五年级在读的蒟蒻,专注于后端,一起见证蒟蒻的成长,您的评论与赞与关注是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。
题目描述
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
题解一
假设这个数组是全闭数组则查找数据时要判断left==right的情况
则left和right的取值要+1
class Solution {
public:
int search(vector<int>& nums, int target) {
int left,right,mid;
left=0,right=nums.size()-1;
while (left <= right)
{
mid=(left+right)/2;
if(nums[mid] == target){
return mid;
}
else if(nums[mid] < target){
left=mid+1;
}
else {
right=mid-1;
}
}
return -1;
}
};
题解二
假设区间范围是半开半闭区间则left和right就不可能相等,循环条件只能是left<right
并且开区间的下标移动不要减一
class Solution {
public:
int search(vector<int>& nums, int target) {
int left,right,mid;
left=0,right=nums.size();
while (left < right)
{
mid=(left+right)/2;
if(nums[mid] == target){
return mid;
}
else if(nums[mid] < target){
left=mid+1;
}
else {
right=mid;
}
}
return -1;
}
};
版权声明
本文为[小学五年级在读的蒟蒻]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44229867/article/details/122361817
边栏推荐
猜你喜欢

2022.2.14-2.27 责任链模式

排序方式(1)==>冒泡排序,简单的选择排序

Cs5518, Mipi to dual LVDS, replacement: gm8775 of Guoteng, tc358775 of Toshiba, dual LVDS, domestic perfect replacement, DSI to dual channel LVDS, LVDS clock frequency up to 154mhz, 1920 x1200

Cjc5340, ADC, DAC, replacement cs5340, digital to analog converter, 100db192khz multi bit audio A / D converter, audio codec100db192khz multi bit audio A / D converter

OSPF multi area

NP, OSPF route aggregation

Define a standard class

Knowledge of classes and objects

【WPF】利用Ellipse或Rectangle制作圆形进度条

Voisins bgp
随机推荐
mysql底层的引擎选择,为什么索引结构选择B+树:(3.28-4.3)
synchronized的底层的三种上锁实现方式:(3.21-3.27)
写入数据进入磁盘文件代码示例如下:
【计组】冯诺依曼体系结构
BGP authentication function
PIM-DM
中介者模式(3.28-4.3)
数据库死锁总结:(3.7-3.13)
论文阅读:Domain Name Encryption Is Not Enough: Privacy Leakage via IP-based Website Fingerprinting
Sorting method (1) = > bubble sorting, simple selection sorting
Longxun series: lt8912b, lt6911c, HDMI to Mipi (CSI \ DSI), single channel mipi2 DSi bridge to LVDS / HDM, hdmi1 4 to dual port mipidsi/csi and audio data sheet
【WPF】数据模板选择器DataTemplateSelector
NP, OSPF virtual link
Signals
Set up MySQL master-slave replication, read-write separation, one master and one slave
Knowledge of classes and objects
Solve the problem of Chinese garbled code
NP、OSPF 故障排除
[untitled] Guoteng GM series, gm8284dd (gm8284dr, lt8218a), gm8285c, gm7123c, lvdsttl to TTL, TTL to single LVDS, TTL digital signal to VGA
BGP neighbor