当前位置:网站首页>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;}}
边栏推荐
- 看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
- QT笔记——在一个窗口上显示另外一个透明窗口
- ansible module --copy module
- Mysql事务隔离级别与MVCC(多版本并发控制)
- MySQL主从复制几个重要的启动选项
- 10份重磅报告 — 展望中国数字经济未来
- excel 批量翻译-excel 批量函数公司翻译大全免费
- 企业级数据治理工作怎么开展?Datahub这样做
- Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
- 21 Days Learning Challenge - Day 1 Punch (Screen Density)
猜你喜欢
随机推荐
5G网络切片技术
故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
力扣209-长度最小的字符串——滑动窗口法
MP的几种查询方式
yolo格式(txt)数据集转VOC(xml)
Oracle 19c 连接PDB
Swift中什么时候不能用 () 代替 Void 来使用
【MySQL】多表联合查询、连接查询、子查询「建议收藏」
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
X86函数调用模型分析
【Acunetix-Forgot your password】
SQL(面试实战07)
Failure Analysis | A SELECT statement crashes MySQL, what happened?
匹配滤波(四种滤波器的幅频特性)
面积曲线AUC(area under curve)
ansible module --copy module
SQL函数 $TRANSLATE