当前位置:网站首页>【剑指Offer】53 - I. 在排序数组中查找数字 I
【剑指Offer】53 - I. 在排序数组中查找数字 I
2022-06-30 16:19:00 【LuZhouShiLi】
剑指 Offer 53 - I. 在排序数组中查找数字 I
题目
统计一个数字在排序数组中出现的次数。
思路
使用二分查找分别找到左边界left和右边界right,所以数字target的数量就是right - left - 1
代码
class Solution {
public int search(int[] nums, int target) {
// 搜索右边界 right
int i = 0,j = nums.length - 1;
while(i <= j)
{
int m = (i + j) / 2;
if(nums[m] < target)
{
i = m + 1;// 说明target在闭区间[m + 1,j] 上
}
else if(nums[m] == target)
{
i = m + 1; // 因为查找右边界 所以 右边界一定在闭区间[m + 1, j]中
}
else
{
j = m -1;// target在闭区间[i,m - 1]中
}
}
int right = i; // 定位右边界 此时right指向的数字 不是target
if(j >= 0 && nums[j] != target) return 0;
// 搜索左边界 right
i = 0;
j = nums.length - 1;
while(i <= j)
{
int m = (i + j) / 2;
if(nums[m] < target)
{
i = m + 1;
}
else{
j = m - 1;
}
}
int left = j;// 左边界指向的数字不是target
return right - left - 1;
}
}
边栏推荐
- In the past, the industrial Internet we knew only appeared as a substitute for the consumer Internet
- leetcode:1042. 不邻接植花【随机填入符合要求的 + 后面不会形成矛盾 + set.pop】
- Redis data structure analysis
- If your MES is not upgraded, it will be eliminated
- Acwing game 57
- ROC-RK3566-PC使用10.1寸IPS触摸屏显示
- [零基础学IoT Pwn] 环境搭建
- 【OpenCV 例程200篇】215. 基于多段线绘制近似椭圆
- EMQ 助力青岛研博建设智慧水务平台
- Interview shock 60: what will cause MySQL index invalidation?
猜你喜欢
基于SSM实现毕业设计管理系统
SSH tool pyqt
商鼎云新版来袭 | 收藏夹功能已上线,满足个人使用需求
Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!
Alibaba cloud disk sharing compressed package
6 張圖帶你搞懂 TCP 為什麼是三次握手?
水平视觉错误效果js特效代码
leetcode:787. K 站中转内最便宜的航班【k步最短路 + dfs记忆化 + defaultdict(dict)】
Property or method “approval1“ is not defined on the instance but referenced during render
生成对抗网络,从DCGAN到StyleGAN、pixel2pixel,人脸生成和图像翻译。
随机推荐
flutter自定义组件
Alibaba cloud disk sharing compressed package
MySQL8 NDB Cluster安装部署
[零基础学IoT Pwn] 环境搭建
中基协:推荐使用电子合同
水平视觉错误效果js特效代码
addmodule_ allmerge_ ams_ im
[200 opencv routines] 215 Drawing approximate ellipse based on polyline
Cesium-1.72 learning (model attitude control)
Parker variable displacement piston pump pv092r1k1t1nmmc
flutter 音乐 录音 播放 audioplayers
Cesium-1.72 learning (eagle eye map of the earth)
面试突击60:什么情况会导致 MySQL 索引失效?
Canvas cloud shape animation
Servlet运行原理_API详解_请求响应构造进阶之路(Servlet_2)
力士乐液控单向阀Z2S10-1-3X/
腾讯云的一场硬仗
[JVM] takes you to learn about the garbage collection mechanism (GC) in the JVM -- including diagrams
【Proteus仿真】Arduino UNO利用74LS148扩展中断
unity粒子_异常显示处理