当前位置:网站首页>记某公司面试算法题:查找一个有序数组某个数字出现的次数
记某公司面试算法题:查找一个有序数组某个数字出现的次数
2022-07-06 09:13:00 【三笠·阿卡曼】
记录
记某公司面试算法题:查找一个有序数组某个数字出现的次数,要求是不能使用暴力破解的方式;
本来知道怎么做,结果因为不会写二分导致没手撕出来,着实够菜的。。
代码
package com.vleus.algorithm.strings;
/** * @author vleus * @date 2021年09月26日 20:26 */
public class GetNumCount {
// public static int getNumCount(int[] array, int num) {
//
// if (array.length == 0) {
// return 0;
// }
//
// int count = 0;
// for (int i = 0; i < array.length; i++) {
// if (array[i] == num) {
// count++;
// }
// }
//
// return count;
// }
//二分查找
private static int times(int[] arr, int n) {
int low = 0;
int high = arr.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (arr[mid] >= n) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public static int getNumCount2(int[] arr, int num) {
int first = times(arr, num);
int last = times(arr, num + 1);
int times = (first == arr.length || arr[first] != num) ? 0 : last - first;
return times;
}
public static void main(String[] args) {
int[] arr = {
1, 2, 3, 3, 3, 4, 5};
System.out.println(getNumCount2(arr,6));
}
}
边栏推荐
- MySQL19-Linux下MySQL的安装与使用
- ++Implementation of I and i++
- MySQL27-索引优化与查询优化
- [paper reading notes] - cryptographic analysis of short RSA secret exponents
- [recommended by bloggers] asp Net WebService background data API JSON (with source code)
- MySQL22-逻辑架构
- API learning of OpenGL (2004) gl_ TEXTURE_ MIN_ FILTER GL_ TEXTURE_ MAG_ FILTER
- CSDN问答标签技能树(一) —— 基本框架的构建
- MySQL完全卸载(Windows、Mac、Linux)
- MySQL21-用戶與權限管理
猜你喜欢
Mysql34 other database logs
Emotional classification of 1.6 million comments on LSTM based on pytoch
API learning of OpenGL (2003) gl_ TEXTURE_ WRAP_ S GL_ TEXTURE_ WRAP_ T
MySQL20-MySQL的数据目录
Case identification based on pytoch pulmonary infection (using RESNET network structure)
La table d'exportation Navicat génère un fichier PDM
Pytoch LSTM implementation process (visual version)
CSDN Q & a tag skill tree (V) -- cloud native skill tree
CSDN question and answer tag skill tree (I) -- Construction of basic framework
Idea import / export settings file
随机推荐
MySQL transaction log
Installation and use of MySQL under MySQL 19 Linux
Mysql36 database backup and recovery
Mysql27 - Optimisation des index et des requêtes
Mysql35 master slave replication
MySQL36-数据库备份与恢复
Mysql25 index creation and design principles
Generate PDM file from Navicat export table
CSDN问答标签技能树(五) —— 云原生技能树
API learning of OpenGL (2002) smooth flat of glsl
[recommended by bloggers] C WinForm regularly sends email (with source code)
February 13, 2022-3-middle order traversal of binary tree
The virtual machine Ping is connected to the host, and the host Ping is not connected to the virtual machine
Mysql26 use of performance analysis tools
February 13, 2022-2-climbing stairs
Yum prompt another app is currently holding the yum lock; waiting for it to exit...
Mysql21 user and permission management
MySQL22-逻辑架构
MySQL19-Linux下MySQL的安装与使用
CSDN博文摘要(一) —— 一个简单的初版实现