当前位置:网站首页>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;}}边栏推荐
猜你喜欢
随机推荐
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
Golang map数组按字段分类
Running yum reports Error: Cannot retrieve metalink for reposit
npm run serve启动报错npm ERR Missing script “serve“
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
10份重磅报告 — 展望中国数字经济未来
翁恺C语言程序设计网课笔记合集
放苹果(暑假每日一题 13)
【云驻共创】数据工坊平台,0代码开发数据处理业务“快”人一步
JSP中如何正确的填写include指令中的file路径呢?
智能手表前景如何?
ssm web page access database data error
学习经验分享之七:YOLOv5代码中文注释
sva assertion data
List排序 ,取最大值最小值
SQL函数 $TRANSLATE
The exchange - string dp
翻译英语的软件-免费翻译软件-各种语言互相翻译
Learning Experience Sharing Seven: YOLOv5 Code Chinese Comments
服务器间传输文件









