[LeetCode#973] K Closest Points to Origin

2024. 8. 8. 12:42·Algorithm/문제풀이

❒ Description


제목 K Closest Points to Origin
링크 https://leetcode.com/problems/k-closest-points-to-origin/description/
자료구조 선형 (우선순위 큐)
시간복잡도 O(nlogn)

 

이번 문제는 우선순위 큐를 사용하여 해결하는 문제이다. Sort, Heap, Quick Select를 사용하는

구현도 있는데 이것에 대해서는 해당 섹션 공부할 때 같이 볼 예정이다.

 

이 문제는 Comparator와 Comparable 중 하나를 사용해서 우선순위를 결정해줘야 한다.

Comparator를 통해서 우선순위를 정해줄 경우 main method에서 `Comparator#compare`메서드를

제정의 해줘야해서 DDD에 어긋난다.

 

반면에 Comparable를 사용하게 되면 Point 클래스가 Comparable 인터페이스를 implement하면 되기 

때문에 Point 도메인이 우선순위 결정하는 로직을 갖고 있게 된다. 이렇게 하면 재사용할 및 수정에 장점을

가져갈 수 있게 된다. 또한 메서들 명(calculateDistanceUsing)을 굉장히 직관적으로 작성할 수 있다.

 

 

 

❒ Solution


1. Comparator

1-1. Point 중첩 클래스

public static class Point {
    long distance;
    int[] point;

    public Point(long distance, int[] point) {
        this.distance = distance;
        this.point = point;
    }
}

 

1-2. main method

public int[][] kClosest(int[][] points, int k) {

    Comparator<Point> pointComp = new Comparator<Point>() {
        @Override
        public int compare(Point o1, Point o2) {
            if (o1.distance == o2.distance) {
                return 0;
            } else if (o1.distance > o2.distance) {
                return 1;
            } else {
                return -1;
            }
        }
    };

    PriorityQueue<Point> pointPQ = new PriorityQueue<>(pointComp);

    for(int[] point : points) {
        pointPQ.add(new Point(calculateDistance(point), point));
    }

    int[][] result = new int[k][2];
    for(int i = 0; i < k; i++) {
        Point target = pointPQ.poll();
        result[i] = target.point;
    }

    return result;
}

private Long calculateDistance(int[] point) {
    return ((long) point[0] * point[0]) + ((long) point[1] * point[1]);
}

 


 

2. Comparable

2-1. Point inner 클래스

public static class Point implements Comparable<Point> {
    long distance;
    int[] point;

    public Point(long distance, int[] point) {
        this.distance = distance;
        this.point = point;
    }

    public Point(int[] point) {
        this.distance = calculateDistanceUsing(point);
        this.point = point;
    }

    private long calculateDistanceUsing(int[] point) {
        return (long) (point[0] * point[0]) + (long) (point[1] * point[1]);
    }

    @Override
    public int compareTo(Point other) {
        return Long.compare(this.distance, other.distance);
    }
}

 

2-2. main method

public int[][] kClosest(int[][] points, int k) {
    PriorityQueue<Point> pq = new PriorityQueue<>();

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

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

'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#46] Permutation  (0) 2024.08.21
[프로그래머스#42576] 완주하지 못한 선수  (0) 2024.08.16
[LeetCode#23] Merge K sorted Lists  (0) 2024.08.06
[LeetCode#641] Design Circular Deque  (0) 2024.08.05
[LeetCode#622] Design Circular Queue  (0) 2024.08.04
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#46] Permutation
  • [프로그래머스#42576] 완주하지 못한 선수
  • [LeetCode#23] Merge K sorted Lists
  • [LeetCode#641] Design Circular Deque
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (166)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    sliding-window
    Back-Tracking
    binarysearch
    부분단조성
    greedy
    Two-Pointer
    오블완
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#973] K Closest Points to Origin
상단으로

티스토리툴바