-
Notifications
You must be signed in to change notification settings - Fork 0
/
1. Two Sum
45 lines (33 loc) · 960 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
36
37
38
39
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++)
{
if(map.containsKey(target - nums[i]))
{
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
-------------------------or ----------------------------------------------
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] sum = new int[2];
for (int i = 0; i < nums.length; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
if (target == nums[i] + nums[j]) {
sum[0] = i;
sum[1] = j;
return sum;
}
}
}
return sum;
}
}