[LeetCode] 1492. The kth Factor of n
Given two positive integers n
and k
.
A factor of an integer n
is defined as an integer i
where n % i == 0
.
Consider a list of all factors of n
sorted in ascending order, return the kth
factor in this list or return -1 if n
has less than k
factors.
Example 1:
Input: n = 12, k = 3 Output: 3 Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
Example 2:
Input: n = 7, k = 2 Output: 7 Explanation: Factors list is [1, 7], the 2nd factor is 7.
Example 3:
Input: n = 4, k = 4 Output: -1 Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
Example 4:
Input: n = 1, k = 1 Output: 1 Explanation: Factors list is [1], the 1st factor is 1.
Example 5:
Input: n = 1000, k = 3 Output: 4 Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000].
Constraints:
1 <= k <= n <= 1000
N 的第 K 个因子。
给你两个正整数 n 和 k 。
如果正整数 i 满足 n % i == 0 ,那么我们就说正整数 i 是整数 n 的因子。
考虑整数 n 的所有因子,将它们 升序排列 。请你返回第 k 个因子。如果 n 的因子数少于 k ,请你返回 -1 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/the-kth-factor-of-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题,我这里提供两种办法,介于数据量不是非常大,其实运行速度看不出区别。
第一种办法就是从 1 到 N 不断地找一个除数去跟 N 做除法,如果这个数字可以被 N 整除,则 count++,当 count == K 的时候,则可以返回那个除数。如果遍历完 N 之后 count < K,则说明 N 的因子不足 K 个,返回 -1。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int kthFactor(int n, int k) { 3 int res = -1; 4 // corner case 5 if (k > n) { 6 return res; 7 } 8 9 // normal case 10 int count = k; 11 for (int i = 1; i <= n; i++) { 12 if (n % i == 0) { 13 count--; 14 res = i; 15 } 16 if (count == 0) { 17 break; 18 } 19 } 20 return count == 0 ? res : -1; 21 } 22 }
第二种办法也类似。注意对于每一个 N 的因子 i ,如果N能被 i 整除,那么一定会产生一个商 N / i 。我们在遍历的时候,可以只遍历到 N 的平方根,然后建立一个 list 来存储商 N / i 。我们从 1 开始扫描到 sqrt(N) ,如果 i * i 不等于 N 则把 n / i 加入 list。这里相当于是用 for 循环记录 N 的一半因子,用 list 去记录 N 的另一半因子。当 count == k 的时候,则说明找到了第 K 个因子,我们就返回这个因子。如果第 K 个因子不在 count 这一边,那么就一定在 list 中,注意 list 里面的数字是从大到小存储的所以注意最后从 list 中拿数字的方法。
时间O(sqrt(N))
空间O(n) - list
Java实现
1 class Solution { 2 public int kthFactor(int n, int k) { 3 List<Integer> list = new ArrayList<>(); 4 int count = 0; 5 for (int i = 1; i * i <= n; i++) { 6 if (n % i == 0) { 7 if (i * i != n) { 8 list.add(n / i); 9 } 10 count++; 11 if (count == k) { 12 return i; 13 } 14 } 15 } 16 if (list.size() + count < k) { 17 return -1; 18 } 19 return list.get(list.size() - (k - count)); 20 } 21 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具