1353. Ratio Line-up
A lab reports its measured ratios as fractions, stored in the array fractions where fractions[i] = [num, den] and den is always positive. Return the indices 0 to n-1 arranged so that the fractions go from the smallest value to the largest. Compare two fractions exactly by cross-multiplication in 64-bit arithmetic rather than by dividing, because floating point can confuse values that are very close together. When two fractions have exactly equal value, the one with the smaller denominator comes first, and if the denominators are also equal, the smaller original index comes first. Return the ordered list of indices, not the fractions themselves. Aim for O(n log n) time and O(n) extra space.
Example 1
- Input:
- fractions = [[1,2],[1,3],[2,5]]
- Output:
- [1,2,0]
- Explanation:
1/3 is less than 2/5, which is less than 1/2, so the order of indices is 1, 2, 0.
Example 2
- Input:
- fractions = [[2,4],[1,2],[3,6],[-1,1]]
- Output:
- [3,1,0,2]
- Explanation:
-1/1 is the smallest; the other three all equal 1/2, so the smaller denominators go first: 1/2, then 2/4, then 3/6.
Example 3
- Input:
- fractions = [[0,5],[0,1],[-3,7]]
- Output:
- [2,1,0]
- Explanation:
-3/7 is negative; 0/1 and 0/5 are both zero and the smaller denominator 1 comes first.
Constraints
1 ≤ n ≤ 1000
-104 ≤ num ≤ 104
1 ≤ den ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)