forked from Lonewolf0502/DeveloperCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo_Sum.java
More file actions
39 lines (30 loc) · 1015 Bytes
/
Two_Sum.java
File metadata and controls
39 lines (30 loc) · 1015 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
34
35
36
37
38
39
// 1. Two Sum
// https://leetcode.com/problems/two-sum/
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
// O(n^2) Solution.
// int output[] = new int[2];
// for(int i = 0; i < nums.length; i++){
// for(int j = i + 1; j < nums.length; j++){
// if(nums[i] + nums[j] == target){
// output[0] = i;
// output[1] = j;
// }
// }
// }
// return output;
// O(n) Solution.
int output[] = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
output[1] = i;
output[0] = map.get(target - nums[i]);
return output;
}
map.put(nums[i], i);
}
return output;
}
}