前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >首先看K一个难看的数字

首先看K一个难看的数字

作者头像
全栈程序员站长
发布2022-07-06 09:28:58
1710
发布2022-07-06 09:28:58
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君。

把仅仅包括质因子2、3和5的数称作丑数(Ugly Number),比如:2,3,4,5,6,8,9,10,12,15,等,习惯上我们把1当做是第一个丑数。 写一个高效算法,返回第n个丑数。

代码语言:javascript
复制
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));
	}

	/**
	 * 寻找第K个丑数
	 * 
	 * @param k
	 * @return
	 */
	public static int findKthUglyNumber(int k) {
		if (k < 0) {
			return 1;// 把第一个丑数返回
		}
		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];// 从0開始
	}

}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/117395.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月6,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档