LeetCode – Two Sum (Java)
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zerobased.
For example:
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=0, index2=1
Java Solution
Use HashMap to store the target value.
public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { int index = map.get(numbers[i]); result[0] = index ; result[1] = i; break; } else { map.put(target  numbers[i], i); } } return result; } } 
Time complexity depends on the put and get operations of HashMap which is normally O(1).
Time complexity of this solution is O(n).
<pre><code> String foo = "bar"; </code></pre>

Jeff

cegprakash

RadhaKrishnan Venkataramani

Tom

Darren Haken

Tom Dawn

Darren Haken

Vatsal Mahajan

suprchan

Mubar

zcr

ravi

YvDa

Brave

d0103

coder

JackyZhuang

ryanlr

ryanlr

Tia

xmpy

Kevin