-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (30 loc) · 934 Bytes
/
Solution.java
File metadata and controls
33 lines (30 loc) · 934 Bytes
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
package two_sum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Solution {
/**
* Solution for 1.TwoSum challenge
* BigO:
* Time complexity: O(n)
* Space complexity: O(n)
*
* @param nums Given an array of integers
* @param target an integer value - nums[i] + nums[j] will be target
* @return An array of integers - [i, j]
*/
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> data = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (data.containsKey(complement)) {
return new int[]{data.get(complement), i};
} else {
data.put(nums[i], i);
}
}
return new int[]{};
}
}