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
The optimal solution to solve this problem is using a HashMap. For each element of the array, (targetnums[i]) and the index are stored in the HashMap.
public int[] twoSum(int[] nums, int target) { if(nums==null  nums.length<2) return new int[]{0,0}; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0; i<nums.length; i++){ if(map.containsKey(nums[i])){ return new int[]{map.get(nums[i]), i}; }else{ map.put(targetnums[i], i); } } return new int[]{0,0}; } 
Time complexity is O(n).
<pre><code> String foo = "bar"; </code></pre>

Olympus

Durga Pradeep

Apoorva

Hitesh

Trendisoft

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