剑指Offer——丑数

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

定义:一个数m是另一个数n的因子,是指n能被m整除,也就是n%m==0;根据丑数的定义,就是一个数能被2整除,就连续除以2;如果能被3整除,就连续除以3;如果能被5整除,就连续除以5;如果最后得到的是1,那么这个数就是丑数,否则不是;

思路一:暴力破解,把传入的参数循环除以2,3,5如果最后==0,就是丑数,否则不是。

public boolean isUgly3(int num) {
    if (num > 0) {
        while (num % 2 == 0) {
            num /= 2;
        }
        while (num % 3 == 0) {
            num /= 3;
        }
        while (num % 5 == 0) {
            num /= 5;
        }
    }
    return num == 1;
}

思路二:用时间换空间。创建一个数组保存已经找到的丑数;创建一个数组,里面的数字都是排好序的丑数,每个丑数都是前面的丑数乘以2,3,5得到的;因为每次数组中新增加一个丑数时,便要加入该丑数*2,3,5;但是如果新增加的丑数前面的丑数乘以2,3,5的结果还未加入数组中,则肯定轮不到他,所以思路如下:

新建数组UglyNumber,数组中第一个数UglyNumber[0]=1;

新建一个数组uglyIndex记录已经乘过2,3,5的丑数在数组中的位置,初始化为{0,0,0};

比如:

  • 当i=1时,之后比较[1*2,1*3,1*5],取最小的数2,此时UglyNumber={1,2}; 表示1已经乘过2了,将乘2的位置向后移动一位;则uglyIndex={1,0,0};之后比较的是[2*2,1*3,1*5];
  • 当i=2时,比较[2*2,1*3,1*5],取最小的数3,此时UglyNumber={1,2,3}表示1已经乘过3了,所以乘3的位置向后移动1位,则uglyIndex={1,1,0};之后比较就是[2*2,2*3,1*5];
  • 当i=3时,比较[2*2,2*3,1*5],取最小的数4,此时UglyNumber={1,2,3,4}表示2已经乘过2了,所以乘2的位置向后移动1位,则uglyIndex={2,1,0};之后比较的是【3*2,2*3,1*5】
  • 以此类推

该方法主要是减少了对于非丑数的计算,节省了时间;

代码:

package Array;

/**
 * 丑数
 * @Author: AnNing
 * @Description:
 * @Date: Create in 20:16 2019/7/24
 */
public class GetUglyNumber {

    final static int [] d = { 2, 3, 5 };
    public static int GetUglyNumber_Solution(int index) {
        if(index == 0) return 0;
        int uglyNumber[] = new int[index];//存放丑数的数组
        uglyNumber[0] = 1;
        int [] indexUgly = new int[] { 0, 0, 0 };//记录数组uglyNumber中分别乘过2,3,5的丑数的位置
        int num[] = new int[] { 2, 3, 5 };//记录比较的三个值
        int cur = 1;

        while (cur < index) {
            int m = finMin(num[0], num[1], num[2]);
            if (uglyNumber[cur - 1] < num[m])
                uglyNumber[cur++] = num[m];
            indexUgly[m] += 1;
            num[m] = uglyNumber[indexUgly[m]] * d[m];
        }
        return uglyNumber[index - 1];
    }

    private static int finMin(int num2, int num3, int num5) {
        int min = Math.min(num2, Math.min(num3, num5));
        return min == num2 ? 0 : min == num3 ? 1 : 2;
    }


    public static void main(String[] args){
        int a=GetUglyNumber_Solution(1500);
        System.out.println(a);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值