FB面经 Prepare: K closest point to the origin

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FB面经 Prepare: K closest point to the origin相关的知识,希望对你有一定的参考价值。

Give n points on 2-D plane, find the K closest points to origin

 

 1 package fbPractise;
 2 
 3 import java.util.*;
 4 
 5 class Coordinate {
 6     int x;
 7     int y;
 8     public Coordinate(int x, int y) {
 9         this.x = x;
10         this.y = y;
11     }
12 }
13 
14 public class Kclosest {
15     
16     public static List<Coordinate> findK(List<Coordinate> input, int k) {
17         HashMap<Coordinate, Integer> map = new HashMap<Coordinate, Integer>();
18         int longest = 0;
19         for (Coordinate each : input) {
20             int distance = cal(each);
21             map.put(each, distance);
22             longest = Math.max(longest, distance);
23         }
24         
25         List<Coordinate>[] arr = new ArrayList[longest + 1];
26         for (Coordinate each : map.keySet()) {
27             int dis = map.get(each);
28             if (arr[dis] == null)
29                 arr[dis] = new ArrayList<Coordinate>();
30             arr[dis].add(each);
31         }
32         
33         List<Coordinate> res = new ArrayList<Coordinate>();
34         for (int i=0; i<arr.length-1 && res.size()<k; i++) {
35             if (arr[i] != null)
36                 res.addAll(arr[i]);
37         }
38         return res;
39     }
40     
41     public static int cal(Coordinate a) {
42         return a.x * a.x + a.y * a.y;
43     }
44     
45 
46     /**
47      * @param args
48      */
49     public static void main(String[] args) {
50         // TODO Auto-generated method stub
51         Coordinate c1 = new Coordinate(1,2);
52         Coordinate c2 = new Coordinate(1,3);
53         Coordinate c3 = new Coordinate(2,5);
54         List<Coordinate> list = new ArrayList<Coordinate>();
55         list.add(c1);
56         list.add(c2);
57         list.add(c3);
58         List<Coordinate> res = findK(list, 2);
59         for (Coordinate each : res) {
60             System.out.print(each.x);
61             System.out.println(each.y);
62         }
63     }
64 
65 }

 

以上是关于FB面经 Prepare: K closest point to the origin的主要内容,如果未能解决你的问题,请参考以下文章

FB面经 Prepare: Make Parentheses valid

K-th Closest Distance

[hdu-6621]K-th Closest Distance 主席树 线段树 2019 多校4

2019 Multi-University Training Contest 4 - K-th Closest Distance

2019杭电多校第三场 1008 K-th Closest Distance

Groupon面经Prepare: Max Cycle Length