FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java-Competitive-Programming/Algorithms/PriorityQueue.java at master · joney000/Java-Competitive-Programming · GitHub
joney000
/
Java-Competitive-Programming
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
123
Code
Issues
0
Pull requests
1
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java-Competitive-Programming
/
Algorithms
/
PriorityQueue.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
36 lines (33 loc) · 1.1 KB
Breadcrumbs
Java-Competitive-Programming
/
Algorithms
/
PriorityQueue.java
Copy path
File metadata and controls
36 lines (33 loc) · 1.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
class
Solution
{
class
Point
{
int
x
,
y
;
int
distance
;
public
Point
(
int
x
,
int
y
){
this
.
x
=
x
;
this
.
y
=
y
;
this
.
distance
=
x
*
x
+
y
*
y
;
}
}
// returns the K Closest points from origin (0, 0)
// Time: O(n log k), space: O(k)
public
int
[][]
kClosest
(
int
[][]
points
,
int
k
) {
if
(
points
.
length
==
0
||
k
>
points
.
length
){
return
null
;
}
int
numPoints
=
points
.
length
;
PriorityQueue
<
Point
>
pQueue
=
new
PriorityQueue
<
Point
>(
k
+
1
, (
a
,
b
) -> (
b
.
distance
-
a
.
distance
));
// max elem on top
for
(
int
[]
point
:
points
){
pQueue
.
add
(
new
Point
(
point
[
0
],
point
[
1
]));
if
(
pQueue
.
size
() >
k
){
pQueue
.
poll
();
}
}
int
[][]
sortedElements
=
new
int
[
k
][
2
];
for
(
int
pos
=
k
-
1
;
pos
>=
0
;
pos
--){
Point
point
= (
Point
)
pQueue
.
poll
();
sortedElements
[
pos
][
0
] =
point
.
x
;
sortedElements
[
pos
][
1
] =
point
.
y
;
}
return
sortedElements
;
}
}
Back
|
FazBrowse Home
|
New Git URL