当前位置:网站首页>[sword finger offer] 53 - I. find the number I in the sorted array
[sword finger offer] 53 - I. find the number I in the sorted array
2022-06-30 17:40:00 【LuZhouShiLi】
The finger of the sword Offer 53 - I. Look up numbers in the sort array I
subject
Count the number of times a number appears in the sort array .
Ideas
Use binary search to find the left boundary respectively left And the right border right, So the numbers target The number of right - left - 1
Code
class Solution {
public int search(int[] nums, int target) {
// Search the right border right
int i = 0,j = nums.length - 1;
while(i <= j)
{
int m = (i + j) / 2;
if(nums[m] < target)
{
i = m + 1;// explain target In the closed zone [m + 1,j] On
}
else if(nums[m] == target)
{
i = m + 1; // Because I want to find the right boundary therefore The right boundary must be in a closed interval [m + 1, j] in
}
else
{
j = m -1;// target In the closed zone [i,m - 1] in
}
}
int right = i; // Locate right boundary here right The number pointing to No target
if(j >= 0 && nums[j] != target) return 0;
// Search left border 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;// The number that the left boundary points to is not target
return right - left - 1;
}
}
边栏推荐
猜你喜欢

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

JS from prototype chain to inheritance
![[zero basic IOT pwn] environment construction](/img/3b/a0689a1570fcc40bb9a5a4e9cdc63c.png)
[zero basic IOT pwn] environment construction

Send the injured baby for emergency medical treatment. Didi's driver ran five red lights in a row

编写C语言的最简单小程序Hello world

TFTP下载kernel,nfs挂载文件系统
![[C language] explain threads - thread separation function pthread_ detach](/img/d7/cce6c8afda85376eb569b1a5239c48.png)
[C language] explain threads - thread separation function pthread_ detach

2022上半年盘点:20+主流数据库重大更新及技术要点汇总

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

每日刷题记录 (九)
随机推荐
Login box tricks
Mysql8 NDB cluster installation and deployment
零基础也能做Apple大片!这款免费工具帮你渲染、做特效、丝滑展示
Splitting. JS text title slow loading JS effect
Cesium-1.72 learning (camera tracking)
Daily question brushing record (IX)
splitting. JS password display hidden JS effect
生成对抗网络,从DCGAN到StyleGAN、pixel2pixel,人脸生成和图像翻译。
AcWing 第 57 场周赛
Exch:exchange server 2013 is about to end support
Map集合
6 张图带你搞懂 TCP 为什么是三次握手?
数据分析新动力——国内首款开源一体化实时HTAP数据库石原子StoneDB发布
EMQ helps Qingdao Yanbo build a smart water platform
Exercise book of introduction to database system
Bridge emqx cloud data to AWS IOT through the public network
Booking UI effect implemented by svg
Network: principle and practice of server network card group technology
NielsenIQ迎来零售实验室负责人Dawn E. Norvell,将加速扩张全球零售战略
Property or method “approval1“ is not defined on the instance but referenced during render