Daily Growing

Leetcode 1. Two Sum(HashMap)

2018-06-18

Given int[] and a target number, return the sequence of the two numbers that can be added to get the target number.

See original question

Ideas

Go through the given int[], for every number A, store its partner’s value as a key and A’s location as a value.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer,Integer> map = new HashMap<>();

for (int i = 0; i < numbers.length; i++) {
if (map.get(numbers[i]) != null) {
int[] result = {map.get(numbers[i]), i};
return result;
}
map.put(target - numbers[i], i);
}
int[] result = {};
return result;
}
}
Tags: