当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
随机推荐
解决导出excel文件名中文乱码的问题
Excel动态图制作
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
华为eNSP(基础实验通信)
Shell编程之条件语句
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
JSP中如何正确的填写include指令中的file路径呢?
yolo格式(txt)数据集转VOC(xml)
如何通过DBeaver 连接 TDengine?
21 Days Learning Challenge - Day 1 Punch (Screen Density)
go源码之sync.Waitgroup
Shell编程案例
图形处理单元(GPU)的演进
当POC遇见RPA:RPA项目顺利实施的关键
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
从幻核疑似裁撤看如何保证NFT的安全
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
SQL函数 TRIM
AQS-AbstractQueuedSynchronizer