1400. Angle Order
A lighthouse at the origin sweeps its beam counter-clockwise, starting from the positive x-axis, and lights up stations in turn. Each station is a point in points given as [x, y]; no station is at the origin.
Return the indices of points ordered by polar angle measured counter-clockwise from the positive x-axis in the range [0, 2*pi). Points with exactly the same angle (the same direction) are ordered by smaller squared distance from the origin first, then by smaller index. Compare angles exactly with integer arithmetic: first classify each point into the upper half-plane (y > 0, or y = 0 and x > 0) or the lower one, then compare two points in the same half with the sign of their cross product. Do not use atan2 or other floating-point angles. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- points = [[1,1],[-1,0],[0,-2],[3,0],[0,1]]
- Output:
- [3,0,4,1,2]
- Explanation:
The angles are 45, 180, 270, 0 and 90 degrees, so the order is the point at index 3, then 0, 4, 1 and 2.
Example 2
- Input:
- points = [[2,2],[1,1],[3,3]]
- Output:
- [1,0,2]
- Explanation:
All three share one direction, so they are ordered by distance: index 1, then 0, then 2.
Constraints
1 ≤ points.length ≤ 1000
-104 ≤ x, y ≤ 104
No point equals (0, 0); duplicates are allowed
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)