您的位置:首页 > Web前端

《剑指offer》——丑数

2015-11-12 21:16 337 查看
T:

题目描述

把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

啥都不说了,都在代码里了……

code:

/**
* T: 丑数
*
* 题目描述
* 把只包含因子2、3和5的数称作丑数(Ugly Number)。
* 例如6、8都是丑数,但14不是,因为它包含因子7。
* 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
*
* date: 2015.11.12  20:43
* @author SSS
*
*/
public class Solution {

/**
* 解题思想:根据丑数的定义,可知:任一个丑数(1,2,3,4,5除外),其基本因子都是2,3,5中的一个,
* 换句话说:每个丑数都是一个较小的丑数与2/3/5的乘积
* 顺着以上思路,我们就找到了一种更为快捷的方式:
* 如果要找第N个丑数,那就把之前所有的丑数都保存下来,让前面的丑数从小到大依次乘以2/3/5,找出一个最小的,作为下一个丑数
* @param index
* @return
*/
public int GetUglyNumber_Solution(int index) {
int nthUglyNums = 0;
// sb吗?非要考虑第0个的情况,毫无意义好不好
if (index == 0) {
return 0;
}

int []array = new int[index > 5 ? index : 5];   // 避免index小于5而导致下面的赋值出错
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

for (int i = 5; i < index; i++) {
int minNums = array[i - 1];
int tempNums = 0;

// 乘以2
for (int j = 0; j < i; j++) {
tempNums = array[j] * 2;
if (tempNums > array[i - 1]) {
minNums = tempNums;
break;
}
}

// 乘以3
for (int j = 0; j < i; j++) {
tempNums = array[j] * 3;
if (tempNums > array[i - 1]) {
minNums = tempNums > minNums ? minNums : tempNums;
break;
}
}

// 乘以5
for (int j = 0; j < i; j++) {
tempNums = array[j] * 5;
if (tempNums > array[i - 1]) {
minNums = tempNums > minNums ? minNums : tempNums;
break;
}
}
array[i] = minNums;
}

nthUglyNums = array[index - 1];

return nthUglyNums;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: