forked from shenzhu/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1. Two Sum.java
More file actions
63 lines (54 loc) · 1.73 KB
/
1. Two Sum.java
File metadata and controls
63 lines (54 loc) · 1.73 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Method One */
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = 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){
//construct result
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
}
/* Method Two */
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//init hashmap
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
//find the complement
int complement;
for(int i = 0; i < nums.length; i++){
complement = target - nums[i];
if(map.containsKey(complement) && map.get(complement) != i){
return new int[] {i, map.get(complement)};
}
}
throw new IllegalArgumentException("No such numbers");
}
}
/* Method Three */
public class Solution {
public int[] twoSum(int[] nums, int target) {
int complement;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//find and store in one iteration
for(int i = 0; i < nums.length; i++){
//find
complement = target - nums[i];
if(map.containsKey(complement)){
return new int[] {map.get(complement), i};
}
//store
map.put(nums[i], i);
}
throw new IllegalArgumentException("No such numbers");
}
}