当前位置:网站首页>【剑指Offer】剑指 Offer 53 - II. 0~n-1中缺失的数字
【剑指Offer】剑指 Offer 53 - II. 0~n-1中缺失的数字
2022-06-30 16:19:00 【LuZhouShiLi】
剑指 Offer 53 - II. 0~n-1中缺失的数字
题目
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
思路
使用二分查找,如果中间元素的值和下标相等,那么下一轮的查找只需要查找右半边;如果中间元素的值和下标不想等,并且前面一个元素和他的下标相等,这就意味着中间的数字正好是第一个值和下标不想等的元素,它的下标就是在数组中不存在的数字;如果中间元素的值和下标不相等,并且它前面的元素和他的下标不相等,那就意味着下一轮查找我们只需要在左半边查找即可。
代码
class Solution {
public:
int missingNumber(vector<int>& nums) {
int left = 0;
int right = nums.size() - 1;
while(left <= right)
{
int mid = (left + right) / 2;
// 如果相等 说明 不相等的元素在右边
if(nums[mid] == mid)
{
left = mid + 1;// 往右边查找
}
else
{
right = mid - 1;// 不相等 说明不相等的元素在左边
}
}
return left;
}
};
边栏推荐
- 基于SSM实现毕业设计管理系统
- Mysql8 NDB cluster installation and deployment
- Exch: database integrity checking
- 中基协:推荐使用电子合同
- List becomes vector list becomes vector list vector
- 【OpenCV 例程200篇】215. 基于多段线绘制近似椭圆
- If your MES is not upgraded, it will be eliminated
- Design of piece counter based on 51 single chip microcomputer
- Map集合
- 小程序容器与物联网结合的方式
猜你喜欢

canvas鼠标控制重力js特效

Cloud practice of key business migration of Internet of things by well-known Internet housing rental service companies
![[200 opencv routines] 215 Drawing approximate ellipse based on polyline](/img/43/fd4245586071020e5aadb8857316c5.png)
[200 opencv routines] 215 Drawing approximate ellipse based on polyline

Hyper-v:在虚拟网络中启用 SR-IOV

canvas云朵形状动画

【C语言】详解线程 — 线程分离函数 pthread_detach

. Net ORM framework hisql practice - Chapter 1 - integrating hisql

MOOG servo valve d661-4577c

parker比例溢流阀RS10R35S4SN1JW

Ningx 1.20.2
随机推荐
If your MES is not upgraded, it will be eliminated
Property or method “approval1“ is not defined on the instance but referenced during render
自旋锁探秘
splitting. JS password display hidden JS effect
k线图快速入门必读
A tough battle for Tencent cloud
EMQ 助力青岛研博建设智慧水务平台
[200 opencv routines] 215 Drawing approximate ellipse based on polyline
addmodule_ allmerge_ ams_ im
Login box tricks
Pref usage record
[proteus simulation] Arduino uno uses 74ls148 to extend interrupt
Exercise book of introduction to database system
Required plug-ins for idea
List becomes vector list becomes vector list vector
5g business is officially commercial. What are the opportunities for radio and television?
Canvas cloud shape animation
nodejs学习笔记二
Horizontal visual error effect JS special effect code
[untitled] write a student achievement and information management system in C language to realize the operation interface, clear screen display of current operation functions, reading and inputting st