Skip to content

Commit cb91dbd

Browse files
authored
Improved task 2386.
1 parent 918f4f6 commit cb91dbd

File tree

3 files changed

+15
-10
lines changed

3 files changed

+15
-10
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1848,7 +1848,7 @@ implementation 'com.github.javadev:leetcode-in-java:1.12'
18481848

18491849
| # | Title | Difficulty | Tag | Time, ms | Time, %
18501850
|------|----------------|-------------|-------------|----------|---------
1851-
| 2386 |[Find the K-Sum of an Array](src/main/java/g2301_2400/s2386_find_the_k_sum_of_an_array/Solution.java)| Hard | Array, Sorting, Heap_(Priority_Queue) | 75 | 100.00
1851+
| 2386 |[Find the K-Sum of an Array](src/main/java/g2301_2400/s2386_find_the_k_sum_of_an_array/Solution.java)| Hard | Array, Sorting, Heap_Priority_Queue | 75 | 100.00
18521852
| 2385 |[Amount of Time for Binary Tree to Be Infected](src/main/java/g2301_2400/s2385_amount_of_time_for_binary_tree_to_be_infected/Solution.java)| Medium | Tree, Binary_Tree, Depth_First_Search, Breadth_First_Search | 20 | 100.00
18531853
| 2384 |[Largest Palindromic Number](src/main/java/g2301_2400/s2384_largest_palindromic_number/Solution.java)| Medium | String, Hash_Table, Greedy | 26 | 100.00
18541854
| 2383 |[Minimum Hours of Training to Win a Competition](src/main/java/g2301_2400/s2383_minimum_hours_of_training_to_win_a_competition/Solution.java)| Easy | Array, Greedy | 0 | 100.00

src/main/java/g2301_2400/s2386_find_the_k_sum_of_an_array/Solution.java

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package g2301_2400.s2386_find_the_k_sum_of_an_array;
22

3-
// #Hard #Array #Sorting #Heap_(Priority_Queue)
3+
// #Hard #Array #Sorting #Heap_Priority_Queue
44
// #2022_08_25_Time_75_ms_(100.00%)_Space_86.8_MB_(33.33%)
55

66
import java.util.Arrays;
@@ -22,14 +22,12 @@ public long kSum(int[] nums, int k) {
2222
pq.offer(new Pair<>(sum, 0));
2323
while (k-- > 1) {
2424
Pair<Long, Integer> top = pq.poll();
25-
if (top != null) {
26-
long s = top.getKey();
27-
int i = top.getValue();
28-
if (i < nums.length) {
29-
pq.offer(new Pair<>(s - nums[i], i + 1));
30-
if (i > 0) {
31-
pq.offer(new Pair<>(s - nums[i] + nums[i - 1], i + 1));
32-
}
25+
long s = top.getKey();
26+
int i = top.getValue();
27+
if (i < nums.length) {
28+
pq.offer(new Pair<>(s - nums[i], i + 1));
29+
if (i > 0) {
30+
pq.offer(new Pair<>(s - nums[i] + nums[i - 1], i + 1));
3331
}
3432
}
3533
}

src/test/java/g2301_2400/s2386_find_the_k_sum_of_an_array/SolutionTest.java

+7
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,11 @@ void kSum() {
1515
void kSum2() {
1616
assertThat(new Solution().kSum(new int[] {1, -2, 3, 4, -10, 12}, 16), equalTo(10L));
1717
}
18+
19+
@Test
20+
void kSum3() {
21+
assertThat(
22+
new Solution().kSum(new int[] {-530219056, 353285209, 493533664}, 6),
23+
equalTo(-36685392L));
24+
}
1825
}

0 commit comments

Comments
 (0)