forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKClosestPointstoOrigin.java
More file actions
38 lines (35 loc) · 1.06 KB
/
KClosestPointstoOrigin.java
File metadata and controls
38 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package LeetCode;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Classname KClosestPointstoOrigin
* @Description TODO
* @Date 19-2-28 下午4:50
* @Created by mao<[email protected]>
*/
public class KClosestPointstoOrigin {
public int[][] kClosest(int[][] points, int K) {
int m=points.length;
int n=points[0].length;
int[][] result=new int[K][n];
HashMap<Integer,Integer> temp=new HashMap<>();
for(int i=0;i<m;i++){
int sqrt=points[i][0]*points[i][0]+points[i][1]*points[i][1];
temp.put(i,sqrt);
}
LinkedHashMap<Integer,Integer> sortedMap=new LinkedHashMap<>();
temp.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x->sortedMap.put(x.getKey(),x.getValue()));
int count=0;
for (Integer k:sortedMap.keySet()){
if(count>=K){
break;
}
result[count++]=points[k];
}
return result;
}
}