K Closest Points to Origin

We have a list of points on the plane. Find the K closest points to the origin (0,0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order. The answer is guaranteed to be unique(except for the order that it is in.)

ํ‰ํŒ ์œ„์˜ points ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ฐ–๊ณ  ์žˆ๋‹ค. ์›์ ์—์„œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด K ๊ฐœ์˜ points ๋ฅผ ์ฐพ์•„๋ผ.

(์—ฌ๊ธฐ์„œ ๋‘ ์  ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋Š” ์œ ํด๋ฆฌ๋“œ์˜ ๊ฑฐ๋ฆฌ์ด๋‹ค.)

์ˆœ์„œ์ƒ๊ด€์—†์ด ์ •๋‹ต์„ ๋ฆฌํ„ดํ•  ์ˆ˜ ์žˆ๋‹ค. ์ •๋‹ต์€ ์œ ์ผ๋ฌด์ดํ•จ์„ ๋ณด์žฅํ•œ๋‹ค.(์ˆœ์„œ ์ œ์™ธ)

Example 1: Input : points =[ [1,3], [-2,2] ], K = 1 Output : [ [-2,2] ]

Example 2: Input : points = [ [3,3], [5,-1], [-2,4] ], K = 2 Output : [ [3,3], [-2,4] ]//[ [-2,4], [3,3] ] ๋„ ์ •๋‹ต ๊ฐ€๋Šฅ

  1. 1 <= K <= points.length <= 10000

  2. -10000 < points[ i ][ 0 ] < 10000

  3. -10000 < points[ i ][ 1 ] < 10000

1. ๋‹ด์„ ๊ทธ๋ฆ‡ ์ •ํ•œ๋‹ค. - List ์ด์šฉ 2. ์•Œ๊ณ ๋ฆฌ์ฆ˜

class point {//๋ฌธ์ œ์—์„œ point ํด๋ž˜์Šค๊ฐ€ ์ฃผ์–ด์ง€๊ฒ ์ง€.
    int x;
    int y;
    point(int pointX, int pointY) { x = pointX; y = pointY;}
}

์•Œ๊ณ ๋ฆฌ์ฆ˜ #1. ์šฐ์„ ์ˆœ์œ„ ํ ์ด์šฉ

  1. ๋‹ด์„ ๊ทธ๋ฆ‡ ์ •ํ•œ๋‹ค. - ์šฐ์„ ์ˆœ์œ„ ํ์™€ ์ •๋‹ต ๋‹ด์„ 2์ฐจ์› ๋ฐฐ์—ด

  2. ํ์— ๋ฐ์ดํ„ฐ ๋„ฃ๋Š”๋‹ค.

  3. ์ •๋‹ต ๋ฐฐ์—ด์— ๋ฐ์ดํ„ฐ ๋„ฃ๋Š”๋‹ค.

class Solution {
    public int[][] kClosest(int[][] points, int K) {
        //1.๋‹ด์„ ๊ทธ๋ฆ‡ ์ƒ์„ฑ
        Queue<int[]> queue = new PriorityQueue<int[]>(points.length,Comp);
        int[][] result = new int[K][2];
        int index=0;
        //2.ํ์— ๋ฐ์ดํ„ฐ ์‚ฝ์ž…
        for(int[] p : points) {
            queue.offer(p);
        }
        //3.result์— ํ๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ ์ €์žฅ
        while(index < K) {//for๋ฐ˜๋ณต๋ฌธ์„ while๋ฌธ์œผ๋กœ ๋‚˜ํƒ€๋ƒˆ๋‹ค๊ณ  ์ƒ๊ฐ
            result[index] = queue.poll();
            index++;
        }
        return result;
        
        
    }
    Comparator<int[]> Comp = new Comparator<int[]>(){
            public int compare(int[] a, int[] b) {
                return (a[0]*a[0] + a[1]*a[1])-(b[0]*b[0] + b[1]*b[1]);
            }
        };
}

๋ฐฐ์šด ๋‚ด์šฉ ์ •๋ฆฌ

  1. ์šฐ์„ ์ˆœ์œ„ ํ ์ผ๋ฐ˜์ ์œผ๋กœ ํ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ผ์‹œ์ ์œผ๋กœ ์Œ“์•„๋‘๊ธฐ ์œ„ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ FIFO์˜ ๊ตฌ์กฐ์ด๋‹ค. ํ•˜์ง€๋งŒ ์šฐ์„ ์ˆœ์œ„ ํ(PriorityQueue)๋Š” ์šฐ์„ ์ˆœ์œ„(PriorityQueue)๋ฅผ ๋จผ์ € ๊ฒฐ์ •ํ•˜๊ณ  ๊ทธ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ์›์†Œ๊ฐ€ ๋จผ์ € ๋‚˜๊ฐ€๋Š” ์ž๋ฃŒ๊ตฌ์กฐ์ด๋‹ค. ์šฐ์„ ์ˆœ์œ„๋Š” ์ฃผ๋กœ ํž™์„ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„๋œ๋‹ค. ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฝ์ž…ํ•  ๋•Œ ์šฐ์„ ์ˆœ์œ„๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ตœ๋Œ€ํž™ ๋˜๋Š” ์ตœ์†Œํž™์„ ๊ตฌ์„ฑํ•˜๊ณ , ๋ฐ์ดํ„ฐ๋ฅผ ๊บผ๋‚ผ ๋•Œ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ์–ป๋Š”๋‹ค. ๋ฃจํŠธ ๋…ธ๋“œ๋ž„ ์‚ญ์ œํ•  ๋•Œ๋Š” ๋นˆ ๋ฃจํŠธ ๋…ธ๋“œ ์œ„์น˜์— ๋งจ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ณ  ์•„๋ž˜๋กœ ๋‚ด๋ ค๊ฐ€๋ฉด์„œ ์œ„์น˜๊ฐ€ ์กฐ์ •๋œ๋‹ค.

Last updated