强整数

61 阅读1分钟

970. 强整数 - 力扣(LeetCode)

给定三个整数 x 、 y  和  bound ,返回 值小于或等于  bound  的所有  强整数  组成的列表 。

如果某一整数可以表示为  xi + yj ,其中整数  i >= 0 且  j >= 0,那么我们认为该整数是一个  强整数 。

你可以按 任何顺序 返回答案。在你的回答中,每个值 最多 出现一次。

示例 1:

输入: x = 2, y = 3, bound = 10
输出: [2,3,4,5,7,9,10]
解释:
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + 3^2

示例  2:

输入: x = 3, y = 5, bound = 15
输出: [2,4,6,8,10,14]

提示:

  • 1 <= x, y <= 100
  • 0 <= bound <= 10^6

思路

本题可以使用枚举求解。首先我们枚举所有的 n,使得 n = x^ii>=0n <= bound,同样的方法枚举出所有的 m = y^ji>=0n <= bound。我们定义一个集合 set,再双层循环所有的 nm,如果 n + m <=bound,就把 n + m 的值存入集合 set 中。set 去重后就是我们要求的解,代码如下。

解题

/**
 * @param {number} x
 * @param {number} y
 * @param {number} bound
 * @return {number[]}
 */
var powerfulIntegers = function (x, y, bound) {
  let xs = [1];
  let ys = [1];
  if (x > 1) {
    let n = x;
    while (n <= bound) {
      xs.push(n);
      n *= x;
    }
  }
  if (y > 1) {
    let n = y;
    while (n <= bound) {
      ys.push(n);
      n *= y;
    }
  }
  const set = new Set();
  for (let i = 0; i < xs.length; i++) {
    for (let j = 0; j < ys.length; j++) {
      let sum = xs[i] + ys[j];
      if (sum <= bound) {
        set.add(sum);
      } else {
        break;
      }
    }
  }
  return Array.from(set);
};