LeetCode 973.K Closest Points to Origin (Java)

Kim Yongbin·2024년 4월 21일
post-thumbnail

문제

K Closest Points to Origin - LeetCode

Code

class Solution {
    public int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> {
            if (getDistance(o1) > getDistance(o2)) return 1;
            else if (getDistance(o1) == getDistance(o2)) return 0;
            else return -1;
        });

        for (int[] point : points) {
            pq.add(point);
        }

        int[][] result = new int[k][2];
        for (int i = 0; i < k; i++) {
            result[i] = pq.poll();
        }
        return result;
    }

    public int getDistance(int[] point) {
        return point[0] * point[0] + point[1] * point[1];
    }
}
# ```

- Priority QueueComparable 인터페이스를 구현하는 방식을 통해 해결하였다.
- 원점으로부터 거리를 기준으로 정렬하여 k개 만큼 뽑아서 반환하였다.
![](https://velog.velcdn.com/images/yongbin97/post/4ece5022-05b9-460f-b826-7e2280d09534/image.png)
profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글