LeetCode - Algorithms - 1492. The kth Factor of n

Problem

1492. The kth Factor of n

Java

simple

© https://leetcode.com/problems/the-kth-factor-of-n/discuss/993800/Java-100-Fast-or-Easy-Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int kthFactor(int n, int k) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0)
count++;
if (count == k)
return i;
}
return -1;
}
}

Submission Detail

  • 207 / 207 test cases passed.
  • Runtime: 1 ms, faster than 43.12% of Java online submissions for The kth Factor of n.
  • Memory Usage: 35.5 MB, less than 90.14% of Java online submissions for The kth Factor of n.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.ArrayList;
import java.util.List;

class Solution {
public int kthFactor(int n, int k) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= n; i++) {
if (n % i == 0)
list.add(i);
}
if (list.size() < k)
return -1;
else
return list.get(k-1);
}
}

Submission Detail

  • 207 / 207 test cases passed.
  • Runtime: 1 ms, faster than 43.15% of Java online submissions for The kth Factor of n.
  • Memory Usage: 35.8 MB, less than 48.68% of Java online submissions for The kth Factor of n.