Skip to content

Commit 73367e1

Browse files
Merge pull request #4239 from andreionoie/4sum-java-sol
Add java solution for CSES Four Sum
2 parents f975eff + 9cdff4e commit 73367e1

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

solutions/gold/cses-1642.mdx

+41-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ of our indices overlap.
2424
**Time Complexity:** $\mathcal{O}(N^2)$
2525

2626
<LanguageSection>
27-
2827
<CPPSection>
2928

3029
```cpp
@@ -63,18 +62,57 @@ int main() {
6362
int idx = x - v[i] - v[j];
6463
if (hm.find(idx) != hm.end()) {
6564
cout << i + 1 << " " << j + 1 << " " << hm[idx].f + 1 << " "
66-
<< hm[idx].s + 1;
65+
<< hm[idx].s + 1 << endl;
6766
return 0;
6867
}
6968
}
7069

7170
for (int j = i + 1; j < n; j++) hm[v[i] + v[j]] = {i, j};
7271
}
7372

74-
cout << "IMPOSSIBLE\n";
73+
cout << "IMPOSSIBLE" << endl;
7574
}
7675
```
7776
7877
</CPPSection>
78+
<JavaSection>
79+
80+
```java
81+
import java.io.*;
82+
import java.util.*;
83+
84+
public class Main {
85+
public static void main(String[] args) {
86+
Kattio io = new Kattio();
87+
int n = io.nextInt();
88+
int x = io.nextInt();
89+
int[] arr = new int[n + 1]; // 1-indexed array for this problem
90+
for (int i = 1; i <= n; i++) { arr[i] = io.nextInt(); }
91+
92+
Map<Integer, int[]> twoSum = new HashMap<>();
93+
for (int i = 1; i <= n; i++) {
94+
for (int j = i + 1; j <= n; j++) {
95+
int differenceToX = x - arr[i] - arr[j];
96+
if (twoSum.containsKey(differenceToX)) {
97+
int k = twoSum.get(differenceToX)[0];
98+
int l = twoSum.get(differenceToX)[1];
99+
io.printf("%d %d %d %d", i, j, k, l);
100+
io.close();
101+
return;
102+
}
103+
}
104+
for (int j = 1; j <= i - 1; j++) {
105+
twoSum.put(arr[j] + arr[i], new int[] {j, i});
106+
}
107+
}
108+
109+
io.println("IMPOSSIBLE");
110+
io.close();
111+
}
112+
113+
// CodeSnip{Kattio}
114+
}
115+
```
79116

117+
</JavaSection>
80118
</LanguageSection>

0 commit comments

Comments
 (0)