当前位置:网站首页>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;}}
边栏推荐
- FinClip | 来了, 2022 年 7 月更新大盘点
- ASP.NET Core 6框架揭秘实例演示[31]:路由&ldquo;高阶&rdquo;用法
- Mysql事务隔离级别与MVCC(多版本并发控制)
- ansible module --yum module
- npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
- 【项目管理技术的优势】
- SQL function TRIM
- 如何通过DBeaver 连接 TDengine?
- SQL函数 TRIM
- 使用kubesphere图形界面创建一个devops的CI/CD流程
猜你喜欢
随机推荐
QListView的使用
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
半夜赶工制作简报的我好想说 : 确定了,最终稿就是这样
FinClip | 来了, 2022 年 7 月更新大盘点
CAN总线的AUTOSAR网络管理
leetcode: 200. Number of islands
力扣209-长度最小的字符串——滑动窗口法
Several reasons why applet plugins benefit developers
服务器间传输文件
OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
翁恺C语言程序设计网课笔记合集
爆款视频怎么做?这里或许有答案!
Camera Hal OEM模块 ---- cmr_snapshot.c
今日睡眠质量记录85分
Create an application operation process using the kubesphere GUI
excel 批量翻译-excel 批量函数公司翻译大全免费
Mysql事务隔离级别与MVCC(多版本并发控制)
Getting Started with Three.JS Programmatic Modeling
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一
How to connect TDengine through DBeaver?