GuilinDev

Lc0973

05 August 2008

973 K Closest Points from 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.)

Example 1:

1
2
3
4
5
6
7
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation: 
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

1
2
3
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)

Note:

  1. 1 <= K <= points.length <= 10000
  2. -10000 < points[i][0] < 10000
  3. -10000 < points[i][1] < 10000

分析

计算哪个点离原点最近,可以利用众所周知的距离公式来计算,但是大可不必用外面的那一层根号,因为仅仅内部平方和就可以用来判断了。

实则是可以转化成了topK问题,所以topK问题的解法都可以用,

1)全排序, time: O(n) = N log(N),space: O(N)

2)堆排序,用maxHeap,大顶堆堆顶元素最大,因为我们要找的是smallest one,我们需要不断判断堆顶的元素与新元素的大小关系。 先加入k个元素(计算后的)到maxheap中。 进行逻辑判断,堆顶和新元素,实施必要的替换,保证heap的size。 简单循环,取出heap中的值到array中,输出。 time: O(n) = Nlog(k),space: O(k)

3)BFPRT算法,快排的思想,time: O(n) = N,space: O(N)

代码

优先掌握,快选模板,将k个原点一次选选到pivot - k的左边,最坏O(n^2),最优O(n),空间复杂度O(1)

将快选模板记住

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
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
    public int[][] kClosest(int[][] points, int k) {
        return quickSelect(points, k, 0, points.length - 1);
    }
    private int[][] quickSelect(int[][] points, int k, int left, int right) {
        while (left < right) {
            int mid = partition(points, left, right);
            if(mid == k) {
                break;
            } else if (mid < k) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return Arrays.copyOf(points, k);
    }
    private int partition(int[][] points, int left, int right) {
        int[] pivot = points[left]; // 快选模板,用left为pivot
        int i = left + 1;
        int j = right;

        while (i <= j) {
            while (i <= j && cal(points[i]) <= cal(pivot)) {
                i++;
            }
            while (i <= j && cal(points[j]) > cal(pivot)) {
                j--;
            }
            if (i > j) {
                break;
            }
            swap(points, i, j);
        }

        swap(points, left, j);

        return j;
    }

    private int cal(int[] a) {
        return a[0] * a[0] + a[1] * a[1];
    }

    private void swap(int[][] points, int i, int j) {
        int[] temp = points[i];
        points[i] = points[j];
        points[j] = temp;
    }
}

全排序

1
2
3
4
5
6
7
8
class Solution {
    public int[][] kClosest(int[][] points, int K) {
        int[][] ans=new int[K][2];
        Arrays.sort(points,(int[] o1,int[] o2)->(o1[0]*o1[0]+o1[1]*o1[1]-o2[0]*o2[0]-o2[1]*o2[1]));
        System.arraycopy(points,0,ans,0,K);
        return ans;
    }
}

堆排序

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
class Solution {
    public int[][] kClosest(int[][] points, int K) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> (cal(b) - cal(a))); // 倒序排列
        // Queue<int[]> priorityQueue = new PriorityQueue<>(K, (o1, o2) -> o1[0] * o1[0] + o1[1] * o1[1] - (o2[0] * o2[0] + o2[1] * o2[1]));

        int[][] result = new int[K][2];
        for (int i = 0; i < K; i++) { // 先加入K个元素
            maxHeap.offer(points[i]);
        }
        for (int i = K; i < points.length; i++) {
            if (cal(maxHeap.peek()) > cal(points[i])) { // 堆顶最大距离要比新来的点大,移出
                maxHeap.poll();
                maxHeap.offer(points[i]);
            }
        }
        
        for (int i = 0; i < K; i++) {
            result[i] = maxHeap.poll();
        }
        return result;
    }
    
    private int cal(int[] a) { // 函数编程计算坐标距离
        return a[0] * a[0] + a[1] * a[1];
    }
}

同样堆排序,略微不同的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int[][] kClosest(int[][] points, int K) {
        if(points.length == 0 || points[0].length == 0) return points;
        
        PriorityQueue<int[]> pq = new PriorityQueue<>(
            (a, b) -> ((a[0]*a[0] + a[1]*a[1]) - (b[0]*b[0] + b[1]*b[1])));
        
        for (int i = 0; i < points.length; i++) { // 先加入所有点
            pq.add(points[i]);
        }
        
        int[][] res = new int[K][2];
        for (int i = 0; i < K; i++) { // 然后取出K个点
            int[] temp = pq.poll();
            res[i][0] = temp[0];
            res[i][1] = temp[1];
        }
        return res;
    }
}

pq不使用lamda

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
39
40
41
42
43
44
45
46
47
class Solution {

    static class Pair implements Comparable<Pair>{
        int first;
        int second[];
        Pair(int first, int second[]){
          this.first = first;
          this.second = second;
        }
        
        public int compareTo(Pair o){
            return this.first - o.first;
        }
        
    }
    
    public int[][] kClosest(int[][] arr, int k) {
        int n = arr.length;
        int dist[] = new int[n];
        PriorityQueue<Pair> pq = new PriorityQueue<>(Collections.reverseOrder());
        
        // calculate distance between them
        for(int i=0; i<n; i++)
            dist[i] = arr[i][0]*arr[i][0] + arr[i][1]*arr[i][1];
        
        
        for(int i=0; i<arr.length; i++){
            pq.add(new Pair(dist[i], arr[i] ));
            
            if(pq.size()>k)
                pq.remove();
        }    
    
        
        int ans[][]= new int[k][2];
        int i=0;
     
        while(!pq.isEmpty()){
          ans[i] = pq.remove().second;
            i++;
        }
        
        return ans;
        
        
    }
}