Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

丑数2 #199

Open
louzhedong opened this issue Jan 22, 2020 · 0 comments
Open

丑数2 #199

louzhedong opened this issue Jan 22, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

编写一个程序,找出第 n 个丑数。

丑数就是只包含质因数 2, 3, 5 的正整数。

示例:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:

1 是丑数。
n 不超过1690。

解答

一个丑数乘以2,乘以3,乘以5,都是丑数。所以可以使用3个游标分别乘以2,3,5,来找出最小的丑数,然后将当前游标加1。每次都可以找出下一个丑数

解答

/**
 * @param {number} n
 * @return {number}
 */
var nthUglyNumber = function (n) {
  var result = [1];
  var cursor1 = 0, cursor2 = 0, cursor3 = 0, min;
  while (result.length < n) {
    min = Math.min(result[cursor1] * 2, result[cursor2] * 3, result[cursor3] * 5);
    if (min === result[cursor1] * 2) {
      cursor1++;
    }
    if (min === result[cursor2] * 3) {
      cursor2++;
    }
    if (min === result[cursor3] * 5) {
      cursor3++;
    }
    result.push(min);
  }
  return result[n - 1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant