码迷,mamicode.com
首页 > 其他好文 > 详细

FB面经 Prepare: K closest point to the origin

时间:2017-03-14 10:24:58      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:log   new   lis   return   auto   points   class   close   ack   

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

标签:log   new   lis   return   auto   points   class   close   ack   

原文地址:http://www.cnblogs.com/EdwardLiu/p/6546969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!