当前位置:网站首页>力扣每日一题-第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;
}
};边栏推荐
- Multiplication, DFS order
- Distributed. Idempotency
- 孩子的编程启蒙好伙伴,自己动手打造小世界,长毛象教育AI百变编程积木套件上手
- ShardingSphere之水平分库实战(四)
- Chi-square distribution of digital image steganography
- ShardingSphere之读写分离(八)
- Parameter introduction and selection points of wireless module
- Ticmp - 更快的让应用从 MySQL 迁移到 TiDB
- 蓝牙mesh系统开发三 Ble Mesh 配网器 Provisioner
- 打印任务排序 js od华为
猜你喜欢

ShardingSphere read-write separation (8)

typescript12-联合类型

孩子的编程启蒙好伙伴,自己动手打造小世界,长毛象教育AI百变编程积木套件上手

typescript12 - union types

ShardingSphere's vertical sub-database sub-table actual combat (5)

斩获BAT、TMD技术专家Offer,我都经历了什么?

ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!

1782. 统计点对的数目 双指针

The Meta Metaverse Division lost 2.8 billion in the second quarter, still want to continue to bet?Metaverse development has yet to see a way out

调度中心xxl-Job
随机推荐
typescript18-对象类型
Teach you how to configure Jenkins automated email notifications
Yolov7实战,实现网页端的实时目标检测
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
822. 走方格
观察者(observer)模式(一)
黄东旭:TiDB的优势是什么?
JS逆向之浏览器补环境(一)
ShardingSphere's public table combat (7)
Rocky/GNU之Zabbix部署(1)
关于Redis相关内容的基础学习
1782. Count the number of point pairs Double pointer
【952. Calculate the maximum component size according to the common factor】
一万了解 Gateway 知识点
软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?
4G通信模块CAT1和CAT4的区别
分布式.幂等性
typescript17 - function optional parameters
VS warning LNK4099: No solution found for PDB
分布式.分布式锁