You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
Example 1:
Input: arr = [1,2,3,5], k = 3 Output: [2,5] Explanation: The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5.
Example 2:
Input: arr = [1,7], k = 1 Output: [1,7]
Constraints:
2 <= arr.length <= 10001 <= arr[i] <= 3 * 104arr[0] == 1arr[i] is a prime number for i > 0.arr are unique and sorted in strictly increasing order.1 <= k <= arr.length * (arr.length - 1) / 2Follow up: Can you solve the problem with better than
O(n2) complexity?
class Solution {
public boolean dfs(
int node,
int[][] adj,
boolean[] visit,
boolean[] inStack
) {
// If the node is already in the stack, we have a cycle.
if (inStack[node]) {
return true;
}
if (visit[node]) {
return false;
}
// Mark the current node as visited and part of current recursion stack.
visit[node] = true;
inStack[node] = true;
for (int neighbor : adj[node]) {
if (dfs(neighbor, adj, visit, inStack)) {
return true;
}
}
// Remove the node from the stack.
inStack[node] = false;
return false;
}
public List<Integer> eventualSafeNodes(int[][] graph) {
int n = graph.length;
boolean[] visit = new boolean[n];
boolean[] inStack = new boolean[n];
for (int i = 0; i < n; i++) {
dfs(i, graph, visit, inStack);
}
List<Integer> safeNodes = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!inStack[i]) {
safeNodes.add(i);
}
}
return safeNodes;
}
}class Solution {
public int[] kthSmallestPrimeFraction(int[] arr, int k) {
Queue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(
Comparator.comparingDouble(e -> (double) e.getKey() / e.getValue()));
IntStream.range(0, arr.length).forEach(i -> IntStream.range(i + 1, arr.length)
.forEach(j -> pq.offer(new java.util.AbstractMap.SimpleEntry<>(arr[i], arr[j]))));
IntStream.range(0, k - 1).forEach(x -> pq.poll());
int[] ans = new int[2];
var m = pq.poll();
ans[0] = m.getKey();
ans[1] = m.getValue();
return ans;
}
}