当前位置:网站首页>力扣每日一题-第46天-704. 二分查找
力扣每日一题-第46天-704. 二分查找
2022-07-31 01:26:00 【重邮研究森】
2022.7.30今天你刷题了吗?
题目:
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
分析:
给定一个升序数组和整型,在这个数组中找到是否存在这个整型,存在则返回下标,不存在则返回-1。
思路:对于查找问题:第一思路就是二分查找。利用两个下标一左一右,分别从两端开始。判断中间的值是否和目标一样,根据大小关系调整下标。
当target>num,则说明目标值在num右边,则left变
当target<num,则说明目标值在num左边,则right变
解析:
1.二分法
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right)
{
int mid = (right - left) / 2 + left;
int num = nums[mid];
if (target > num)
{
left = mid + 1;
}
else if (target < num)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
};2.暴力法
直接对数组进行遍历,当遍历的元素小于target一直遍历,当出现相等则返回下标,当出现大于情况则返-1
class Solution {
public:
int search(vector<int>& nums, int target) {
int i=0;
while(i<nums.size()-1&&nums[i]<target)
{
i++;
}
if(nums[i]!=target)
{
i=-1;
}
return i;
}
};边栏推荐
- The difference between 4G communication module CAT1 and CAT4
- 这个项目太有极客范儿了
- Multiplication, DFS order
- Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化
- Installation problem corresponding to tensorflow and GPU version
- In Google Cloud API gateway APISIX T2A and T2D performance test
- 观察者(observer)模式(一)
- VS warning LNK4099: No solution found for PDB
- Artificial Intelligence and Cloud Security
- 蓝牙mesh系统开发二 mesh节点开发
猜你喜欢

ShardingSphere之水平分库实战(四)

【网络安全】文件上传靶场通关(1-11关)

第一学年课程期末考试

Installation problem corresponding to tensorflow and GPU version

typescript17-函数可选参数

使用PageHelper实现分页查询(详细)

This project is so geeky

typescript15- (specify both parameter and return value types)

软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?

【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)
随机推荐
深度学习可以求解特定函数的参数么?
tkinter模块高级操作(二)—— 界面切换效果、立体阴影字效果及gif动图的实现
Responsive layout vs px/em/rem
Bert usage and word prediction based on Keras_bert model
Chi-square distribution of digital image steganography
typescript17 - function optional parameters
JS逆向之浏览器补环境(一)
Know what DTU is 4GDTU equipment
解析云原生消息流系统 Apache Pulsar 能力及场景
4G通信模块CAT1和CAT4的区别
24. 请你谈谈单例模式的优缺点,注意事项,使用场景
ShardingSphere's vertical sub-database sub-table actual combat (5)
Problem record in the use of TypeScript
蓝牙mesh系统开发三 Ble Mesh 配网器 Provisioner
Basic Parameters of RF Devices 1
Word 表格跨页,仍然显示标题
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
射频器件的基本参数2
设置浏览器滚动条样式
ROS Action通信