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. ๋ด์ ๊ทธ๋ฆ ์ ํ๋ค. - List ์ด์ฉ 2. ์๊ณ ๋ฆฌ์ฆ
class point {//๋ฌธ์ ์์ point ํด๋์ค๊ฐ ์ฃผ์ด์ง๊ฒ ์ง.
int x;
int y;
point(int pointX, int pointY) { x = pointX; y = pointY;}
}
์๊ณ ๋ฆฌ์ฆ #1. ์ฐ์ ์์ ํ ์ด์ฉ
๋ด์ ๊ทธ๋ฆ ์ ํ๋ค. - ์ฐ์ ์์ ํ์ ์ ๋ต ๋ด์ 2์ฐจ์ ๋ฐฐ์ด
ํ์ ๋ฐ์ดํฐ ๋ฃ๋๋ค.
์ ๋ต ๋ฐฐ์ด์ ๋ฐ์ดํฐ ๋ฃ๋๋ค.
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]);
}
};
}
๋ฐฐ์ด ๋ด์ฉ ์ ๋ฆฌ
์ฐ์ ์์ ํ ์ผ๋ฐ์ ์ผ๋ก ํ๋ ๋ฐ์ดํฐ๋ฅผ ์ผ์์ ์ผ๋ก ์์๋๊ธฐ ์ํ ์๋ฃ๊ตฌ์กฐ๋ก FIFO์ ๊ตฌ์กฐ์ด๋ค. ํ์ง๋ง ์ฐ์ ์์ ํ(PriorityQueue)๋ ์ฐ์ ์์(PriorityQueue)๋ฅผ ๋จผ์ ๊ฒฐ์ ํ๊ณ ๊ทธ ์ฐ์ ์์๊ฐ ๋์ ์์๊ฐ ๋จผ์ ๋๊ฐ๋ ์๋ฃ๊ตฌ์กฐ์ด๋ค. ์ฐ์ ์์๋ ์ฃผ๋ก ํ์ ์ด์ฉํ์ฌ ๊ตฌํ๋๋ค. ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ํ ๋ ์ฐ์ ์์๋ฅผ ๊ธฐ์ค์ผ๋ก ์ต๋ํ ๋๋ ์ต์ํ์ ๊ตฌ์ฑํ๊ณ , ๋ฐ์ดํฐ๋ฅผ ๊บผ๋ผ ๋ ๋ฃจํธ ๋ ธ๋๋ฅผ ์ป๋๋ค. ๋ฃจํธ ๋ ธ๋๋ ์ญ์ ํ ๋๋ ๋น ๋ฃจํธ ๋ ธ๋ ์์น์ ๋งจ ๋ง์ง๋ง ๋ ธ๋๋ฅผ ์ฝ์ ํ๊ณ ์๋๋ก ๋ด๋ ค๊ฐ๋ฉด์ ์์น๊ฐ ์กฐ์ ๋๋ค.
Last updated
Was this helpful?