当前位置:网站首页>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;}}边栏推荐
猜你喜欢

当POC遇见RPA:RPA项目顺利实施的关键

excel 批量翻译-excel 批量函数公司翻译大全免费

细学常用类,集合类,IO流

企业级数据治理工作怎么开展?Datahub这样做

Mysql transaction isolation level and MVCC (multi-version concurrency control)

OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)

力扣977-有序数组的平方——暴力法&双指针法

【kali-信息收集】(1.8)ARP侦查工具_Netdiscover

免费的中英文翻译软件-自动批量中英文翻译软件推荐大全

雷克萨斯,锁死的安全,挡不住的心寒
随机推荐
Breaking the Boundary, Huawei's Storage Journey
Getting Started with Three.JS Programmatic Modeling
Kotlin的协程与生命周期
Shell编程案例
力扣977-有序数组的平方——暴力法&双指针法
go源码之sync.Waitgroup
21 Days Learning Challenge - Day 1 Punch (Screen Density)
项目监控六大事项
AdguardHome如何配置设置?我的AdguardHome配置内容过滤器拦截列表
jvmxmx和xms参数分析(设定优化校准)
基于深度学习的裂缝检测技术
注意力机制
ASP.NET Core 6框架揭秘实例演示[31]:路由&ldquo;高阶&rdquo;用法
记录代码
QListView的使用
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
腾讯云云函数SCF—入门须知
SQLAlchemy使用教程
npm run serve启动报错npm ERR Missing script “serve“
【Acunetix-忘记密码】