Find the Smallest K Elements in an Array

Given one point P0 on a 2-dimension space. There are n other points on the same space.

Try to find K points which are most closed to P0.

hint:

  Part of Quick Sort. Just sort the useful part of the array.

  1 public class findKPoints {
  2     class Point {
  3         int x;
  4         int y;
  5         public Point(int x, int y) {
  6             this.x = x;
  7             this.y = y;
  8         }
  9     }
 10
 11     Point p0;
 12     ArrayList<Point> points = new ArrayList<Point>();
 13     int k;
 14
 15     public void setSpace() {
 16         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 17         System.out.println("Please set the position of p0 in format ‘x,y‘:");
 18         try {
 19             String[] str = reader.readLine().split(",");
 20             this.p0 = new Point(Integer.parseInt(str[0]), Integer.parseInt(str[1]));
 21         } catch (IOException e) {
 22             e.printStackTrace();
 23             System.exit(1);
 24         }
 25         System.out.println("Please set the position of other points in format ‘x,y‘, type ‘OK‘ when done:");
 26         try {
 27             String tmp = reader.readLine();
 28             while (!tmp.equals("OK")) {
 29                 String[] str = tmp.split(",");
 30                 this.points.add(new Point(Integer.parseInt(str[0]), Integer.parseInt(str[1])));
 31                 tmp = reader.readLine();
 32             }
 33             if (this.points.size()==0) {
 34                 System.err.print("no other points on the space");
 35             }
 36         } catch (IOException e) {
 37             e.printStackTrace();
 38         }
 39         System.out.println("Please give the number of closest points you want to find:");
 40         try {
 41             this.k = Integer.parseInt(reader.readLine());
 42             if (k > points.size()) {
 43                 System.err.println("not enough points");
 44                 System.exit(1);
 45             }
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         }
 49     }
 50
 51     public void find() {
 52         int[][] dist = new int[points.size()][2];
 53         for (int i = 0; i < points.size(); i++) {
 54             dist[i][0] = calculateDis(p0, points.get(i));
 55             dist[i][1] = i;
 56         }
 57         sort(dist, k, 0, dist.length-1);
 58         for (int i = 0; i < k; i++) {
 59             int p = dist[i][1];
 60             System.out.print("("+points.get(p).x+", "+points.get(p).y+") ");
 61         }
 62         System.out.println();
 63     }
 64
 65     public void sort(int[][] dist, int k, int start, int end) {
 66         int dis = dist[start][0];
 67         int p = dist[start][1];
 68         int i = start, j = end;
 69         while (i < j) {
 70             while (i < j && dist[j][0] >= dis) {
 71                 j--;
 72             }
 73             dist[i][0] = dist[j][0];
 74             dist[i][1] = dist[j][1];
 75             while (i<j && dist[i][0] < dis) {
 76                 i++;
 77             }
 78             dist[j][0] = dist[i][0];
 79             dist[j][1] = dist[i][1];
 80         }
 81         dist[i][0] = dis;
 82         dist[i][1] = p;
 83         if (i-start == k-1) {
 84             return;
 85         } else if (i-start > k-1) {
 86             sort(dist, k, start, i);
 87         } else {
 88             sort(dist, k-(i-start+1), i+1, end);
 89         }
 90     }
 91
 92     public int calculateDis(Point p1, Point p2) {
 93         return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
 94     }
 95
 96     public static void main(String[] args) {
 97         findKPoints kp = new findKPoints();
 98         kp.setSpace();
 99         kp.find();
100     }
101 }

The execute of the program

Please set the position of p0 in format ‘x,y‘:
0,0
Please set the position of other points in format ‘x,y‘, type ‘OK‘ when done:
1,1
1,3
-1,0
1,2
4,4
2,1
0,2
OK
Please give the number of closest points you want to find:
5
(-1, 0) (1, 1) (0, 2) (1, 2) (2, 1) 
时间: 2024-10-16 09:53:06

Find the Smallest K Elements in an Array的相关文章

good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)

这是本人在研究leetcode中Median of Two Sorted Arrays一题目的时候看到一篇文章,觉得非常好,其中对快速排序重新实现. 文章来源于http://www.geeksforgeeks.org/这个网站. We recommend to read following post as a prerequisite of this post. K'th Smallest/Largest Element in Unsorted Array | Set 1 Given an ar

[email&#160;protected] Sorting Elements of an Array by Frequency (Sort)

http://www.practice.geeksforgeeks.org/problem-page.php?pid=493 Sorting Elements of an Array by Frequency Given an array of integers, sort the array according to frequency of elements. For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3,

K Closest In Sorted Array - Medium

Given a target integer T, a non-negative integer K and an integer array A sorted in ascending order, find the K closest numbers to T in A. Assumptions A is not null K is guranteed to be >= 0 and K is guranteed to be <= A.length Return A size K integ

maximum sum of a subarray with at-least k elements.

// Returns maximum sum of a subarray with at-least // k elements. static int maxSumWithK(int a[], int n, int k) { // maxSum[i] is going to store maximum sum // till index i such that a[i] is part of the // sum. int maxSum[] = new int [n]; maxSum[0] =

Leetcode-5147 Decrease Elements To Make Array Zigzag(递减元素使数组呈锯齿状)

1 #define _for(i,a,b) for(int i = (a);i < b;i ++) 2 typedef long long ll; 3 using namespace std; 4 5 class Solution 6 { 7 public: 8 int movesToMakeZigzag(vector<int>& nums) 9 { 10 int rnt1 = 0; 11 int rnt2 = 0; 12 13 _for(i,1,nums.size()) 14

poj 3399 Product(数学)

主题链接:http://poj.org/problem?id=3399 Product Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2837   Accepted: 686   Special Judge Description There is an array of N integer numbers in the interval from -30000 to 30000. The task is to sele

poj 3399 Product(数学题)

题目链接:http://poj.org/problem?id=3399 Product Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2837   Accepted: 686   Special Judge Description There is an array of N integer numbers in the interval from -30000 to 30000. The task is to sele

PKU3399贪心

原题http://poj.org/problem?id=3399 Product Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 2839   Accepted: 688   Special Judge Description There is an array of N integer numbers in the interval from -30000 to 30000. The task is to select 

Leetcode: Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10