-
Notifications
You must be signed in to change notification settings - Fork 4
/
1. Two Sum
35 lines (34 loc) · 939 Bytes
/
1. Two Sum
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
//O(n) time and O(n) space
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
int n = nums.length;
Map<Integer, Integer> map = new HashMap();
for(int i=0;i<n;i++){
if(map.containsKey(target-nums[i])){
result[0] = map.get(target-nums[i]);
result[1] = i;
return result;
}
map.put(nums[i], i);
}
return result;
}
}
//O(n^2) time and O(1) space
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
int n = nums.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int sum = nums[i] + nums[j];
if(sum==target){
result[0] = i;
result[1] = j;
}
}
}
return result;
}
}