当前位置:网站首页>力扣每日一题-第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
- 使用PageHelper实现分页查询(详细)
- 297. 二叉树的序列化与反序列化
- Teach you how to configure Jenkins automated email notifications
- "Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
- 一万了解 Gateway 知识点
- 权限管理怎么做的?
- Solution: Parameter 0 of method ribbonServerList in com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfigu
- JS逆向之浏览器补环境(一)
- 【952. 按公因数计算最大组件大小】
猜你喜欢

Parameter introduction and selection points of wireless module

Google官方控件ShapeableImageView使用

深度学习可以求解特定函数的参数么?

Typescript14 - (type) of the specified parameters and return values alone

Installation problem corresponding to tensorflow and GPU version

typescript12-联合类型

RTL8720DN开发笔记一 环境搭建与mqtt实例

This project is so geeky

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

ROS Action通信
随机推荐
ROS2系列知识(3):环境配置
MySQL (6)
The difference between 4G communication module CAT1 and CAT4
MySQL高级-六索引优化
35. Reverse linked list
typescript12-联合类型
无线模块的参数介绍和选型要点
Bert usage and word prediction based on Keras_bert model
【952. Calculate the maximum component size according to the common factor】
Analyze the capabilities and scenarios of the cloud native message flow system Apache Pulsar
typescript13 - type aliases
MySQL——数据库的查,增,删
数字图像隐写术之JPEG 隐写分析
深度学习可以求解特定函数的参数么?
《实战》基于情感词典的文本情感分析与LDA主题分析
《实战》基于电商领域的词性提取及其决策树模型建模
权限管理怎么做的?
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
使用docker安装mysql
基于Keras_bert模型的Bert使用与字词预测