website/content.en/ChapterFour/0700~0799/0786.K-th-Smallest-Prime-Fraction.md
A sorted list A contains 1, plus some number of primes. Then, for every p < q in the list, we consider the fraction p/q.
What is the K-th smallest fraction considered? Return your answer as an array of ints, where answer[0] = p and answer[1] = q.
Examples:
Input: A = [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, 2/3.
The third fraction is 2/5.
Input: A = [1, 7], K = 1
Output: [1, 7]
Note:
A will have length between 2 and 2000.A[i] will be between 1 and 30000.K will be between 1 and A.length * (A.length - 1) / 2.A sorted list A contains 1 and some other primes. When p<q for every pair in the list, we can construct a fraction p/q.
So what is the k-th smallest fraction? Return your answer in the form of an integer array, where answer[0] = p and answer[1] = q.
Note:
package leetcode
import (
"sort"
)
// Solution 1: Binary search
func kthSmallestPrimeFraction(A []int, K int) []int {
low, high, n := 0.0, 1.0, len(A)
// Since binary search is performed on decimals, we cannot terminate the loop with mid+1 and boundary checks as in an integer range
// Therefore, end the loop here based on count
for {
mid, count, p, q, j := (high+low)/2.0, 0, 0, 1, 0
for i := 0; i < n; i++ {
for j < n && float64(A[i]) > float64(mid)*float64(A[j]) {
j++
}
count += n - j
if j < n && q*A[i] > p*A[j] {
p = A[i]
q = A[j]
}
}
if count == K {
return []int{p, q}
} else if count < K {
low = mid
} else {
high = mid
}
}
}
// Solution 2: Brute force, time complexity O(n^2)
func kthSmallestPrimeFraction1(A []int, K int) []int {
if len(A) == 0 || (len(A)*(len(A)-1))/2 < K {
return []int{}
}
fractions := []Fraction{}
for i := 0; i < len(A); i++ {
for j := i + 1; j < len(A); j++ {
fractions = append(fractions, Fraction{molecule: A[i], denominator: A[j]})
}
}
sort.Sort(SortByFraction(fractions))
return []int{fractions[K-1].molecule, fractions[K-1].denominator}
}
// Fraction define
type Fraction struct {
molecule int
denominator int
}
// SortByFraction define
type SortByFraction []Fraction
func (a SortByFraction) Len() int { return len(a) }
func (a SortByFraction) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a SortByFraction) Less(i, j int) bool {
return a[i].molecule*a[j].denominator < a[j].molecule*a[i].denominator
}