-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path1.two-sum.java
More file actions
32 lines (20 loc) · 831 Bytes
/
1.two-sum.java
File metadata and controls
32 lines (20 loc) · 831 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
/* 1.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hmap.containsKey(complement)) {
result[0] = hmap.get(complement);
result[1] = i;
return result;
}
hmap.put(nums[i], i);
}
return result;
}
}