1492. The kth Factor of n

Naive

T: O(n)

S: O(n)

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

Naive with early return

because we only want kth factor, so if we find it, we return it immediately

T: O(n)

S: O(k)

Naive with k--

but actually we don't need to store the factor

T: O(n)

S: O(1)

T: O(sqrt(n)

S: O(1)

but I think this one is tricky, because don't know why, i < sqrt -> here need use double type sqrt...

or it's wrong....

Last updated

Was this helpful?