Skip to content

Commit 1a39460

Browse files
committed
One-Hundred-Sixty-Seven Commit: Add 'K' Closest Numbers problem to Top K Elements section
1 parent 4577b69 commit 1a39460

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed

src/Top_K_Elements/Problem_5_K_Frequent_Numbers.java renamed to src/Top_K_Elements/Problem_5_Top_K_Frequent_Numbers.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import java.util.*;
77

8-
public class Problem_5_K_Frequent_Numbers {
8+
public class Problem_5_Top_K_Frequent_Numbers {
99
public List<Integer> findTopKFrequentNumbers(int[] nums, int k) {
1010

1111
Map<Integer, Integer> numFrequencyMap = new HashMap<>();
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package Top_K_Elements;
2+
3+
// Problem Statement: 'K' Closest Numbers (medium)
4+
// LeetCode Question: 658. Find K Closest Elements
5+
6+
import java.util.ArrayList;
7+
import java.util.Collections;
8+
import java.util.List;
9+
import java.util.PriorityQueue;
10+
11+
public class Problem_8_K_Closest_Number {
12+
13+
class Entry {
14+
int key;
15+
int value;
16+
17+
public Entry(int key, int value) {
18+
this.key = key;
19+
this.value = value;
20+
}
21+
}
22+
23+
public List<Integer> findClosestElements(int[] arr, int K, Integer X) {
24+
int index = binarySearch(arr, X);
25+
int low = index - K, high = index + K;
26+
low = Math.max(low, 0); // 'low' should not be less than zero
27+
// 'high' should not be greater the size of the array
28+
high = Math.min(high, arr.length - 1);
29+
30+
PriorityQueue<Entry> minHeap = new PriorityQueue<>((n1, n2) -> n1.key - n2.key);
31+
// add all candidate elements to the min heap, sorted by their absolute difference
32+
// from 'X'
33+
for (int i = low; i <= high; i++)
34+
minHeap.add(new Entry(Math.abs(arr[i] - X), i));
35+
36+
// we need the top 'K' elements having smallest difference from 'X'
37+
List<Integer> result = new ArrayList<>();
38+
for (int i = 0; i < K; i++)
39+
result.add(arr[minHeap.poll().value]);
40+
41+
Collections.sort(result);
42+
return result;
43+
}
44+
45+
private static int binarySearch(int[] arr, int target) {
46+
int low = 0;
47+
int high = arr.length - 1;
48+
while (low <= high) {
49+
int mid = low + (high - low) / 2;
50+
if (arr[mid] == target)
51+
return mid;
52+
if (arr[mid] < target) {
53+
low = mid + 1;
54+
} else {
55+
high = mid - 1;
56+
}
57+
}
58+
if (low > 0) {
59+
return low - 1;
60+
}
61+
return low;
62+
}
63+
64+
}

0 commit comments

Comments
 (0)