当前位置:网站首页>[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;
}
}
边栏推荐
- 【剑指Offer】剑指 Offer 53 - II. 0~n-1中缺失的数字
- Alibaba cloud disk sharing compressed package
- Booking UI effect implemented by svg
- 构建基本buildroot文件系统
- New power of data analysis -- the first open source integrated real-time HTAP database in China was released by stonedb
- Horizontal visual error effect JS special effect code
- IEEE TBD SCI影响因子提升至4.271,位列Q1区!
- Acwing game 57
- Cloud practice of key business migration of Internet of things by well-known Internet housing rental service companies
- 4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
猜你喜欢
随机推荐
【C语言】详解线程 — 开启两个线程
Parker proportional overflow valve rs10r35s4sn1jw
[C language] detailed explanation of threads - multi threads for collaborative operation
3D图表有效提升数据大屏档次
[C language] explain threads - start two threads
[C language] explain threads - thread separation function pthread_ detach
新技能:通过代码缓存加速 Node.js 的启动
Property or method “approval1“ is not defined on the instance but referenced during render
Cloud practice of key business migration of Internet of things by well-known Internet housing rental service companies
Map collection
期未课程设计:基于SSM的产品销售管理系统
In the past, the industrial Internet we knew only appeared as a substitute for the consumer Internet
流批一体在京东的探索与实践
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
Exch:修复丢失的系统邮箱
高等数学(第七版)同济大学 总习题一 个人解答
力士乐液控单向阀Z2S10-1-3X/
Exch: database integrity checking
Rexroth hydraulic control check valve z2s10-1-3x/
Ten thousand volumes - list sorting [01]









