top k closest points to origin, k closest points to <0,0,0>

大班文档有java solution 强化 5

 x.y z is similar 

class KClosest{
  class Point{
    int x;
    int y;
    
    public Point(int x, int y){
      this.x = x;
      this.y = y;
    }
    
  }
  
  public List<Point> kClosest(List<Point> input, int k){
    ArrayList<Point> res = new ArrayList<>();
    
    // maintain a max heap of size k 
    // everytime we see a point smaller than the point at the top of the max heap
    // we poll the point at the max of the heap out and push the smaller one in 
    // after we are done iteratoing thru every point , we are able to get the k points 
    // and poll them, put them into the list, and reverse it 
    
    PriorityQueue<Point> maxHeap = new PriorityQueue maxHeap<Point>(int k, new Comparator(Point a, Point b){
      @Override
      public int compare(Point a, Point b){
        int disA = a.x * a.x + a.y * a.y;
        int disbB = b.x * b.x + b.y * b.y;
        if(disA < disB){
          return 1;
        }else if(disA > disB){
          return -1;
        }else{
          return 0;
        }
      }
    });
    
    
    // put k points into the max heap first 
    for(int i = 0; i < k; i++){
      maxHeap = new PriorityQueue<Point>();
      maxHeap.push(input.get(i));
    }
    
    
    // and then compare with the rest 
    for(int i = k; i < input.size(); i++){
      if(maxHeap.peek() > input.get(i)){
        maxHeap.poll();
        maxHeap.push(input.get(i));
      }
    }
    
    for(int i = 0; i < k; i++){
      res.add(maxHeap.poll());
    }
    
    return Collections.reverse(res);
  }
}
    

 

posted on 2018-08-11 03:47  猪猪&#128055;  阅读(157)  评论(0)    收藏  举报

导航