当前位置:网站首页>记某公司面试算法题:查找一个有序数组某个数字出现的次数
记某公司面试算法题:查找一个有序数组某个数字出现的次数
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));
}
}
边栏推荐
- MySQL24-索引的数据结构
- Moteur de stockage mysql23
- MySQL23-存儲引擎
- Mysql22 logical architecture
- Mysql23 storage engine
- Just remember Balabala
- CSDN question and answer tag skill tree (II) -- effect optimization
- CSDN问答标签技能树(一) —— 基本框架的构建
- CSDN question and answer tag skill tree (I) -- Construction of basic framework
- Mysql34 other database logs
猜你喜欢

MySQL19-Linux下MySQL的安装与使用

A trip to Macao - > see the world from a non line city to Macao

CSDN问答标签技能树(一) —— 基本框架的构建

Postman environment variable settings

Redis的基础使用

Mysql25 index creation and design principles

Mysql21 user and permission management

Pytoch LSTM implementation process (visual version)

La table d'exportation Navicat génère un fichier PDM

CSDN markdown editor
随机推荐
MySQL 29 other database tuning strategies
frp内网穿透那些事
February 13, 2022-3-middle order traversal of binary tree
MySQL transaction log
How to find the number of daffodils with simple and rough methods in C language
CSDN blog summary (I) -- a simple first edition implementation
Install mysql5.5 and mysql8.0 under windows at the same time
MySQL35-主从复制
Pytoch LSTM implementation process (visual version)
[recommended by bloggers] background management system of SSM framework (with source code)
Adaptive Bezier curve network for real-time end-to-end text recognition
【博主推荐】SSM框架的后台管理系统(附源码)
Bytetrack: multi object tracking by associating every detection box paper reading notes ()
CSDN question and answer module Title Recommendation task (I) -- Construction of basic framework
Mysql21 user and permission management
Idea import / export settings file
Mysql30 transaction Basics
@Controller, @service, @repository, @component differences
Windows cannot start the MySQL service (located on the local computer) error 1067 the process terminated unexpectedly
MySQL other hosts cannot connect to the local database