有些數的素因子只有 3,5,7,請設計一個算法找出第 k 個數。注意,不是必須有這些素因子,而是必須不包含其他的素因子。例如,前幾個數按順序應該是 1,3,5,7,9,15,21。
示例 1:
輸入: k = 5
輸出: 9
class Solution { public int getKthMagicNumber(int k) { int[] res = new int[k]; res[0] = 1; int point3 = 0; int point5 = 0; int point7 = 0; for(int i = 1; i < k; i++) { int count = Math.min(Math.min(res[point3] * 3, res[point5] * 5), res[point7] * 7); if(count % 3 == 0) { point3++; } if(count % 5 == 0) { point5++; } if(count % 7 == 0) { point7++; } res[i] = count; } return res[k - 1]; } }
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/get-kth-magic-number-lcci
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。