Skip to content

Commit 73e0b95

Browse files
committed
Add solution #786
1 parent 3c6f4cf commit 73e0b95

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,7 @@
596596
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
597597
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
598598
785|[Is Graph Bipartite?](./0785-is-graph-bipartite.js)|Medium|
599+
786|[K-th Smallest Prime Fraction](./0786-k-th-smallest-prime-fraction.js)|Medium|
599600
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
600601
791|[Custom Sort String](./0791-custom-sort-string.js)|Medium|
601602
796|[Rotate String](./0796-rotate-string.js)|Easy|

Diff for: solutions/0786-k-th-smallest-prime-fraction.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 786. K-th Smallest Prime Fraction
3+
* https://leetcode.com/problems/k-th-smallest-prime-fraction/
4+
* Difficulty: Medium
5+
*
6+
* You are given a sorted integer array arr containing 1 and prime numbers, where all the integers
7+
* of arr are unique. You are also given an integer k.
8+
*
9+
* For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
10+
*
11+
* Return the kth smallest fraction considered. Return your answer as an array of integers of size
12+
* 2, where answer[0] == arr[i] and answer[1] == arr[j].
13+
*/
14+
15+
/**
16+
* @param {number[]} arr
17+
* @param {number} k
18+
* @return {number[]}
19+
*/
20+
var kthSmallestPrimeFraction = function(arr, k) {
21+
const n = arr.length;
22+
let left = 0;
23+
let right = 1;
24+
25+
while (left < right) {
26+
const mid = (left + right) / 2;
27+
let count = 0;
28+
let maxFraction = [0, 1];
29+
let j = 1;
30+
31+
for (let i = 0; i < n - 1; i++) {
32+
while (j < n && arr[i] > mid * arr[j]) {
33+
j++;
34+
}
35+
36+
count += n - j;
37+
38+
if (j < n && arr[i] * maxFraction[1] > maxFraction[0] * arr[j]) {
39+
maxFraction = [arr[i], arr[j]];
40+
}
41+
}
42+
43+
if (count === k) {
44+
return maxFraction;
45+
} else if (count < k) {
46+
left = mid;
47+
} else {
48+
right = mid;
49+
}
50+
}
51+
52+
return [];
53+
};

0 commit comments

Comments
 (0)