-
-
Notifications
You must be signed in to change notification settings - Fork 611
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
find k closest numbers problem statement and neat solution
- Loading branch information
Sherali Obidov
committed
Aug 30, 2017
1 parent
ac7b45b
commit d9bd77f
Showing
3 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package problems.medium; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.List; | ||
import java.util.PriorityQueue; | ||
|
||
/** | ||
* @author Sherali Obidov. | ||
*/ | ||
public class FindKClosestElements { | ||
|
||
public List<Integer> findClosestElements(List<Integer> arr, int k, int x) { | ||
List<Integer> list= new ArrayList<>(); | ||
if(arr==null || arr.size()==0 || k==0)return list; | ||
|
||
PriorityQueue<Integer> q= new PriorityQueue<>((a, b)-> { | ||
int d= (Math.abs(x-a))-(Math.abs(x-b)); | ||
if(d==0)return a-b; | ||
return d; | ||
}); | ||
q.addAll(arr); | ||
if(q.size()<k)return list; | ||
for(int i=0; i<k; i++){ | ||
list.add(q.remove()); | ||
} | ||
Collections.sort(list); | ||
return list; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters