当前位置:网站首页>First, look at K, an ugly number
First, look at K, an ugly number
2022-07-06 18:25:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
Include only qualitative factors 2、3 and 5 The number of is called ugly (Ugly Number), such as :2,3,4,5,6,8,9,10,12,15, etc. , It's customary for us to 1 As the first ugly number . Write an efficient algorithm , Back to page n Ugly number .
import static java.lang.Math.min;
import static java.lang.System.out;
public class UglyNumber {
public static void main(String[] args) {
out.println(findKthUglyNumber(1500));
}
/**
* Search for the first K Ugly number
*
* @param k
* @return
*/
public static int findKthUglyNumber(int k) {
if (k < 0) {
return 1;// Return the first ugly number
}
int[] numbers = new int[k];
numbers[0] = 1;
int next = 1;
int ugly2Index = 0;
int ugly3Index = 0;
int ugly5Index = 0;
while (next < k) {
int uglyNum = min(numbers[ugly2Index] * 2,
min(numbers[ugly3Index] * 3, numbers[ugly5Index] * 5));
numbers[next] = uglyNum;
while (numbers[ugly2Index] * 2 <= numbers[next]) {
ugly2Index++;
}
while (numbers[ugly3Index] * 3 <= numbers[next]) {
ugly3Index++;
}
while (numbers[ugly5Index] * 5 <= numbers[next]) {
ugly5Index++;
}
next++;
}
return numbers[k - 1];// from 0 Start
}
}Copyright notice : This article is an original blog article , Blog , Without consent , Shall not be reproduced .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117395.html Link to the original text :https://javaforall.cn
边栏推荐
猜你喜欢

传输层 拥塞控制-慢开始和拥塞避免 快重传 快恢复
![[swoole series 2.1] run the swoole first](/img/cd/88abf7e83e9d9d416051b33263690b.png)
[swoole series 2.1] run the swoole first

Penetration test information collection - CDN bypass

關於這次通信故障,我想多說幾句…

win10系统下插入U盘有声音提示却不显示盘符

Shangsilicon Valley JUC high concurrency programming learning notes (3) multi thread lock

Windows连接Linux上安装的Redis

STM32按键状态机2——状态简化与增加长按功能

C language exchanges two numbers through pointers
![[the 300th weekly match of leetcode]](/img/a7/16b491656863e2c423ff657ac6e9c5.png)
[the 300th weekly match of leetcode]
随机推荐
declval(指导函数返回值范例)
Splay
2022暑期项目实训(二)
node の SQLite
Brief description of SQL optimization problems
Shangsilicon Valley JUC high concurrency programming learning notes (3) multi thread lock
文档编辑之markdown语法(typora)
On time and parameter selection of asemi rectifier bridge db207
[Android] kotlin code writing standardization document
虚拟机VirtualBox和Vagrant安装
TCP packet sticking problem
DOM简要
UFIDA OA vulnerability learning - ncfindweb directory traversal vulnerability
简单易用的PDF转SVG程序
Cocos2d Lua 越来越小样本 内存游戏
具体说明 Flume介绍、安装和配置
Transport layer congestion control - slow start and congestion avoidance, fast retransmission, fast recovery
2022 Summer Project Training (III)
Principle and usage of extern
IP, subnet mask, gateway, default gateway