美文网首页
313. 超级丑数

313. 超级丑数

作者: 漫行者_ | 来源:发表于2021-08-10 00:22 被阅读0次

https://leetcode-cn.com/problems/super-ugly-number/
看见这个题目的时候只能大概记得分成几行,然后每一行取最小的,那个最小的行乘一个数,具体怎么做以及忘记。
丑数在leetcode里面有几道题,得先做完前面的,好做后面的。

263. 丑数

class Solution {
    public boolean isUgly(int n) {
        if(num == 0) return false;
        boolean is = false;
        while(num%2 == 0) num = num/2;
        while(num%3 == 0) num= num/3;
        while(num%5 == 0) num = num/5;
        if(num == 1) return true;
        return false;
    }
}

264. 丑数 II

有两种方法,第一种是通过堆,和set实现。堆来取最小的,set来去重。
第二种通过指针的办法,但因为存在重复的情况,有可能index会一起加,所以不能用else if。且第一个数为1.数组循环的话必须从i=1开始。

    public int nthUglyNumber(int n) {
        if (n < 6) return n;
        int ugly[] = new int[n];
        ugly[0] = 1;
        int factor2 = 2, factor3 = 3, factor5 = 5;
        int index2 = 0, index3 = 0, index5 = 0;
        for (int i = 1; i < n; i++) {
            int min = Math.min(factor2, Math.min(factor3, factor5));
            ugly[i] = min;
            if (factor2 == min)
                factor2 = 2 * ugly[++index2];
            if (factor3 == min)
                factor3 = 3 * ugly[++index3];
            if (factor5 == min)
                factor5 = 5 * ugly[++index5];
        }
        return ugly[n-1];
    }

本题的思路和264题的解题思路一模一样。

 public  int nthSuperUglyNumber(int n, int[] primes) {
        int[] array = new int[n];
        int[] indexs = new int[primes.length];
        int[] nums= Arrays.copyOf(primes, primes.length);
        array[0] = 1;
        if (n == 1) return 1;
        for (int i = 1; i < n; i++) {
            int min = Arrays.stream(nums).min().getAsInt();
            array[i] = min;
            for (int j = 0; j < nums.length; j++) {
                if (min == nums[j]) {
                    indexs[j]++;
                    nums[j] = array[indexs[j]] * primes[j];
                }

            }
        }
        return array[n-1];
    }

相关文章

  • 313. 超级丑数

    leetcode

  • 313. 超级丑数

    编写一段程序来查找第 n 个超级丑数。 超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中的正整...

  • 313. 超级丑数

    https://leetcode-cn.com/problems/super-ugly-number/[https...

  • 313:超级丑数

    题意 超级丑数是一个正整数,并满足其所有质因数都出现在质数数组 primes 中。给你一个整数 n 和一个整数数组...

  • leetcode_313_超级丑数

    题目: 编写一段程序来查找第 n 个超级丑数。超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中...

  • 力扣(LeetCode) - 313 超级丑数

    一、题目 编写一段程序来查找第 n 个超级丑数。 超级丑数是指其所有质因数都是长度为 k 的质数列表 primes...

  • Day81 超级丑数

    直接抄星主的: 编写一段程序来查找第 n 个超级丑数。 超级丑数是指其所有质因数都是长度为 k 的质数列表 pri...

  • 2019-02-19

    LeetCode 313. Super Ugly Number Description Write a progr...

  • 263、丑数(E)

    判断一个正整数是否为一个丑数。丑数的定义是 1 为丑数,只包含 2、3、5的数就是丑数,比如 4,8,但是14 就...

  • golang实现剑指offer:动态规划题型

    丑数 LeetCode 面试题49:丑数 题目描述 我们把只包含因子 2、3 和 5 的数称作丑数(Ugly Nu...

网友评论

      本文标题:313. 超级丑数

      本文链接:https://www.haomeiwen.com/subject/cdptbltx.html