-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
36 lines (28 loc) · 923 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package org.example.problems.two_sum;
import org.example.problems.SolutionInterface;
import java.util.HashMap;
import java.util.Map;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Two Sum";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/two-sum/";
}
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numberPositions = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int current = nums[i];
int secondKey = numberPositions.getOrDefault(target - current, -1);
if (secondKey != -1) {
return new int[]{secondKey, i};
}
if (!numberPositions.containsKey(current)) {
numberPositions.put(current, i);
}
}
return new int[]{-1, -1};
}
}