当前位置:网站首页>Likou Daily Question - Day 46 - 704. Binary Search
Likou Daily Question - Day 46 - 704. Binary Search
2022-07-31 01:39:00 【Heavy Mail Research Sen】
2022.7.30 Did you write the questions today?
Title:
Given an n-element sorted (ascending) integer array nums and a target value target , write a function to search for target in nums and return the subscript if the target value exists, otherwise return -1.
Analysis:
Given an ascending array and an integer, find out whether the integer exists in the array, return the subscript if it exists, or -1 if it does not exist.
Ideas: For the search problem: The first idea is binary search.Use two subscripts, one left and one right, to start from both ends.Determine whether the middle value is the same as the target, and adjust the subscript according to the size relationship.
When target>num, it means that the target value is on the right of num, then left changes
When target
Analysis:
1. Dichotomy
class Solution {public:int search(vector& 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. Violence Law
Directly traverse the array. When the traversed element is less than the target, it will continue to traverse. When it is equal, it returns the subscript, and when it is greater than the situation, it returns -1
class Solution {public:int search(vector& nums, int target) {int i=0;while(i
边栏推荐
- ShardingSphere's vertical sub-database sub-table actual combat (5)
- TiDB 在多点数字化零售场景下的应用
- 小黑leetcode之旅:117. 填充每个节点的下一个右侧节点指针 II
- Jetpack Compose学习(8)——State及remeber
- 有没有可以做副业可以日入300元方法?
- 查看zabbix-release-5.0-1.el8.noarch.rpm包内容
- 认识DTU什么是4GDTU设备
- android的webview缓存相关知识收集
- Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
- 黄东旭:TiDB的优势是什么?
猜你喜欢
Mysql: Invalid default value for TIMESTAMP
GCC Rust获批将被纳入主线代码库,或将于GCC 13中与大家见面
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
进程间通信学习笔记
斩获BAT、TMD技术专家Offer,我都经历了什么?
35. Reverse linked list
C language _ structure pointer array function voting system
TiCDC 架构和数据同步链路解析
16、注册中心-consul
【Mysql】——索引的深度理解
随机推荐
【flask入门系列】Flask-SQLAlchemy的使用
蓝牙mesh系统开发二 mesh节点开发
1.非类型模板参数 2.模板的特化 3.继承讲解
Multiplication, DFS order
SQLserver查询最近三个月的数据,语句该怎么写sqlserver
Kyushu cloud as cloud computing standardization excellent member unit
分布式.分布式锁
斩获BAT、TMD技术专家Offer,我都经历了什么?
Ticmp - 更快的让应用从 MySQL 迁移到 TiDB
Mysql:Invalid default value for TIMESTAMP
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
Jetpack Compose学习(8)——State及remeber
剑指offer17---打印从1到最大的n位数
使用docker安装mysql
Installation problem corresponding to tensorflow and GPU version
《实战》基于电商领域的词性提取及其决策树模型建模
射频器件的基本参数2
Analyze the capabilities and scenarios of the cloud native message flow system Apache Pulsar
Word 表格跨页,仍然显示标题
软件测试要达到一个什么水平才能找到一份9K的工作?