当前位置:网站首页>力扣704. 二分查找
力扣704. 二分查找
2022-06-30 04:45:00 【智慧的人不要秃头】

class Solution {
public:
int search(vector<int>& nums, int target) {
//此种二分写法是将target放在一个左闭右闭的区间里,也就是[left,right]中
//所以令left指向数组的第一个元素的下标位置,令right在数组最后一个元素的下标的位置。
int n = nums.size();
int left = 0;
int right = n-1;
int mid = 0; //中间元素的下标,定义在while循环外面是为避免频繁的创建,因为在while循环里面,每一次循环的开始都要确定mid的大小。
//<=是因为left = right是有意义的。
while(left <= right){
//相当于mid = (left + right) / 2,应尽量不这样写,因为当left和right数值很大的时候,相加可能会造成数据的溢出。
mid = (right - left) /2 + left;
//如果当前mid处的元素值正好等于target的话,直接返回mid
if(nums[mid] == target){
return mid;
}
//如果当前mid处的元素值大于target的话,那么说明要找的目标值在mid的左侧,所以将right-1
else if(nums[mid] > target){
right = mid - 1;
continue;
}
//如果当前mid处的元素值小于target的话,那么说明要找的目标值在mid的右侧,所以将left-1
else{
left = mid + 1;
continue;
}
}
//此种情况说明目标值不在nums数组中,所以返回-1
return -1;
}
//时间复杂度:O(logn),其中 n 是数组的长度。
//空间复杂度:O(1)。
};边栏推荐
- Interprocess communication
- 破局存量客群营销,试一下客户分群管理(含聚类模型等实操效果评估)
- Difference between TCP three handshakes and four waves and tcp/udp
- Dual domain SSL certificate
- File and IO
- Create a simple battle game with photon pun
- 【Paper】2017_ Research on coordinated control method of underwater vehicle formation marine survey
- Directory operations and virtual file systems
- Foreign SSL certificate
- 為什麼win10開熱點後電腦沒有網絡?
猜你喜欢

Why does the computer have no network after win10 is turned on?

Network high concurrency

The golden deer, a scenic spot in London -- a sailing museum that tells vivid sailing stories

Collective system

深度学习------不同方法实现Inception-10

【Paper】2021_ Analysis of the Consensus Protocol of Heterogeneous Agents with Time-Delays

Process architecture and process management

National Museum of Singapore - give you spiritual and physical satisfaction

为什么win10开热点后电脑没有网络?

Learn about threads
随机推荐
brew安装nvm报nvm command not found解决方案
Sailing experience not to be missed in New York Tourism: take you to enjoy the magnificent city scenery from different perspectives
Difference between TCP three handshakes and four waves and tcp/udp
力扣2049:统计最高分的节点数目
Redis implements SMS login function (I) traditional session login
HTC vive cosmos development - handle button event
[control] multi agent system summary. 4. control agreement.
Deep learning ----- different methods to realize inception-10
Summary of the reasons why transactional doesn't work
Moore Manor diary I: realize the reclamation, sowing, watering and harvest in Moore Manor
Connect to the database and run node JS running database shows that the database is missing
Webots learning notes
Lambda&Stream
IO stream, character read / write, copy
Singapore parent-child tour, these popular attractions must be arranged
Unity lens making
【Paper】2017_ Distributed control for high-speed trains movements
Autowired注解警告的解决办法
The most comprehensive summary notes of redis foundation + advanced project in history
The subsystem implementing transaction persistence in DBMS is ()