-
Notifications
You must be signed in to change notification settings - Fork 0
/
kClosestPonts.cpp
89 lines (67 loc) · 1.94 KB
/
kClosestPonts.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//^ Given a list of points and a number k, find the k closest points to the origin.
#include <iostream>
bool pairExists(int foundArray[], int key, int size) //* O(k)
{
for (size_t i = 0; i < size; i++)
{
if (foundArray[i] == key)
{
return true;
}
}
return false;
}
void closestPointsFromCenter(int arr[][2],int size,int k)
{
int foundPointIndicies[k]{-1};
int index = 0;
int maxXPoint = arr[0][0];
int maxYPoint = arr[0][1];
int maxIndex = -1;
//^ we have to find the max element from the pairs
for (size_t i = 1; i < size; i++) //* 0(n)
{
if (arr[i][0] >= maxXPoint and arr[i][1] > maxYPoint)
{
maxXPoint = arr[i][0];
maxYPoint = arr[i][1];
maxIndex = i;
}
}
for (int i = 0; i < size; i++) //* 0(nxn)
{
int currentXPoint = maxXPoint;
int currentYPoint = maxYPoint;
int shortestIndex = maxIndex;
for (int j = 0; j < size; j++)
{
//^ Checking if the current point is less then the last point and also checking if it already exists in the foundPoints list
if ((arr[j][0] <= currentXPoint and arr[j][1] < currentYPoint) and !pairExists(foundPointIndicies,j,index))
{
currentXPoint = arr[j][0];
currentYPoint = arr[j][1];
shortestIndex = j;
}
}
foundPointIndicies[index] = shortestIndex;
index++;
}
//* 0(k)
for (int i = 0; i < k; i++) //^ printing the k closest points from the center
{
std::cout<<arr[foundPointIndicies[i]][0]<<" "<<arr[foundPointIndicies[i]][1]<<"\n";
}
}
int main()
{
int points[][2]{
{1, 1},
{3, 3},
{4, 4},
{2, 2},
{-1, -1},
{4,5}};
int k = 2;
closestPointsFromCenter(points, 6, k);
return 0;
}