当前位置:网站首页>Likou 704 - binary search
Likou 704 - binary search
2022-08-02 11:45:00 【Zhang Ran Ran √】
Title description
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.
Solution ideas
This is a simple question. Since the question is given in an ordered array, the binary search method can be used to find elements;
Ascending order and descending order are only partially different when judging boundary conditions;
To find the middle element, you can directly write int mid = (left + right) / 2;
But writing this way, when the size of the array is large, it is easy to cause integer data overflow;
So consider using bitwise operations int mid=left + ((right - left) >> 1);
The interval used is the left and right closed interval [left, right], which I think is better understood.
Input and output example

Code
class Solution {public int search(int[] nums, int target) {int n = nums.length;if(target < nums[0] || target > nums[n - 1]) return -1;int left = 0, right = n - 1;while(left <= right){//int mid = left + ((right - left) >> 1); // this is written to prevent overflow of out-of-integer dataint mid = (left + right) / 2;if(target > nums[mid]){left = mid + 1;}else if(target < nums[mid]){right = mid - 1;}else return mid;}return -1;}}边栏推荐
- Coroutines and Lifecycle in Kotlin
- AdguardHome如何配置设置?我的AdguardHome配置内容过滤器拦截列表
- OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
- Create an application operation process using the kubesphere GUI
- 使用kubesphere图形界面创建一个devops的CI/CD流程
- SQL函数 $TRANSLATE
- 爆款视频怎么做?这里或许有答案!
- Mysql事务隔离级别与MVCC(多版本并发控制)
- Golang map数组按字段分类
- leetcode: 200. Number of islands
猜你喜欢

Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)

Shell编程之条件语句

npm run serve启动报错npm ERR Missing script “serve“

yolo格式(txt)数据集转VOC(xml)

【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan

【kali-信息收集】(1.8)ARP侦查工具_Netdiscover
[email protected] This version of tar is no longer supported, and will not receive"/>npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive

使用mosquitto过程中的问题解决

大疆P4M云遮挡矫正

Create an application operation process using the kubesphere GUI
随机推荐
QListView的使用
sva assertion data
故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?
X86函数调用模型分析
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
Failure Analysis | A SELECT statement crashes MySQL, what happened?
网站自动翻译-网站批量自动翻译-网站免费翻译导出
字母交换--字符串dp
暑期总结3
JSP中如何正确的填写include指令中的file路径呢?
服务器间传输文件
pyqt5连接MYSQL数据库问题
Oracle 单实例19.11升级到19.12
Crack detection technology based on deep learning
go语言的接口
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
jacoco的学习以及理解
List排序 ,取最大值最小值
redis cluster cluster, the ultimate solution?
MySQL主从复制几个重要的启动选项