当前位置:网站首页>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笔记——QT类反射机制简单学习
QT笔记——Q_PROPERTY了解
Shell编程之条件语句
go源码之sync.Waitgroup
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
解决导出excel文件名中文乱码的问题
JVM简介
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
Create your own app applet ecosystem with applet containers
ansible模块--yum模块
10份重磅报告 — 展望中国数字经济未来
Oracle 单实例19.11升级到19.12
受邀出席Rust开发者大会|Rust如何助力量化高频交易?
What is the future of smartwatches?
面积曲线AUC(area under curve)
ssm web page access database data error
记录代码
excel 批量翻译-excel 批量函数公司翻译大全免费
Create an application operation process using the kubesphere GUI
AQS-AbstractQueuedSynchronizer









