Skip to content

Commit 69f96b1

Browse files
add 1711
1 parent 080a37e commit 69f96b1

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

Diff for: src/main/java/com/fishercoder/solutions/secondthousand/_1711.java

+11-7
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,28 @@
55

66
public class _1711 {
77
public static class Solution1 {
8-
private static final long MODUALR = 1000000007;
8+
/**
9+
* This is a very brilliant solution:
10+
* 1. go through each number only once: for each number, we iterate through all possible power of twos, at max, there's only 21 due to the constraints of this problem;
11+
* 2. since it's asking for the sum of two, we can check we have encountered the other number before using a hashmap
12+
*/
913

1014
public int countPairs(int[] deliciousness) {
15+
final long MODULAR = 1000000007;
1116
Map<Integer, Integer> map = new HashMap<>();
1217
long pairs = 0;
13-
for (int i = 0; i < deliciousness.length; i++) {
18+
for (int del : deliciousness) {
1419
int power = 1;
1520
//we only need to go up to 21 since one of the constraints is: 0 <= deliciousness[i] <= 2 to the power of 20
1621
for (int j = 0; j < 22; j++) {
17-
if (map.containsKey(power - deliciousness[i])) {
18-
pairs += map.get(power - deliciousness[i]);
19-
pairs %= MODUALR;
22+
if (map.containsKey(power - del)) {
23+
pairs += map.get(power - del);
2024
}
2125
power *= 2;
2226
}
23-
map.put(deliciousness[i], map.getOrDefault(deliciousness[i], 0) + 1);
27+
map.put(del, map.getOrDefault(del, 0) + 1);
2428
}
25-
return (int) pairs;
29+
return (int) (pairs % MODULAR);
2630
}
2731

2832
}

Diff for: src/test/java/com/fishercoder/secondthousand/_1711Test.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
package com.fishercoder.secondthousand;
22

33
import com.fishercoder.solutions.secondthousand._1711;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static org.junit.Assert.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
88

99
public class _1711Test {
1010
private static _1711.Solution1 solution1;
1111
private static int[] deliciousness;
1212

13-
@BeforeClass
14-
public static void setup() {
13+
@BeforeEach
14+
public void setup() {
1515
solution1 = new _1711.Solution1();
1616
}
1717

0 commit comments

Comments
 (0)