当前位置:网站首页>剑指 Offer 笔记: T53 - I. 在排序数组中查找数字
剑指 Offer 笔记: T53 - I. 在排序数组中查找数字
2022-07-27 10:58:00 【无知小九】
T53 - I. 在排序数组中查找数字 I
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
思路
二分, 寻找target和target-1的右边界, 相减就是答案了
解法 1
class Solution {
public int search(int[] nums, int target) {
return rightMargin(nums, target) - rightMargin(nums, target-1);
}
int rightMargin(int[] nums, int target){
int left =0, right =nums.length-1;
while(left<=right){
int mid = left+((right-left)>>1);
if(nums[mid]>target){
right = mid-1;
}else if(nums[mid]<=target){
left = mid+1;
}
}
return left;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了**100.00%**的用户
内存消耗:41.3 MB, 在所有 Java 提交中击败了**63.01%**的用户
时间复杂度:O(logn)。二分查找的时间复杂度是O(logn)
空间复杂度:O(1)。只需要保存左右边界和中间值即可
边栏推荐
- Game theory acwing 892. Step Nim game
- VSCode复制代码时去掉样式/语法高亮/代码高亮/黑色背景
- C programming language (2nd Edition) -- Reading Notes -- 1.5
- Error while unzipping file in win10: unable to create symbolic link. You may need to run WinRAR with administrator privileges. The client does not have the required privileges
- 容斥原理 AcWing 890. 能被整除的数
- 求组合数 AcWing 888. 求组合数 IV
- 2022 Niuke multi school training (3) a-ancestor topic translation
- Markdown editor syntax - setting of text color, size, font and background color (Reprint)
- Backpack model acwing 1022. Collection of pet elves
- Moveit2 - 1. Start
猜你喜欢

Game theory acwing 891. Nim game

第7章 异常处理

Memory search acwing 901. Skiing

Error encountered in adding quick open option to right-click menu:

Codeforces round #664C

Longest ascending subsequence model acwing 1012. Sister Cities

为什么选择智能电视?

你真的会写二分查找吗——变种二分查找

Basic use of cmake

State compression DP acwing 91. shortest Hamilton path
随机推荐
什么是私域流量?
CTF crypto RSA getting started
树形DP AcWing 285. 没有上司的舞会
Digital triangle model acwing 1015. Picking flowers
VSCode复制代码时去掉样式/语法高亮/代码高亮/黑色背景
博弈论 AcWing 893. 集合-Nim游戏
局域网SDN硬核技术内幕 24 展望未来——RDMA(中)
When std:: bind meets this
Modelarts voice detection and text classification
求组合数 AcWing 888. 求组合数 IV
局域网SDN硬核技术内幕 23 展望未来——RDMA(上)
Basic use of cmake
Knapsack model acwing 423. Picking herbs
C programming language (2nd Edition) -- Reading Notes -- 1.5.3
Find the combination number acwing 885. find the combination number I
Maker Hongmeng application development training 04
torch‘ has no attribute ‘inference_mode‘
Solve importerror: cannot import name'abs'import tensorflow error
数据包传输:应用层-内核-硬件
Ask the big guys, is there transaction control for using flick sink data to MySQL? If at a checkpoint