Two Sum

LeetCode Q 1 - Two Sum

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.

Solution

Code:

public int[] twoSum(int[] nums, int target) {
	Map<Integer, Integer> map = new HashMap<>();
	for (int i = 0; i < nums.length; i++) {
		if (map.containsKey(target - nums[i]))
			return new int[] {map.get(target - nums[i]), i};
		map.put(nums[i], i);
	}
	return new int[2];
}

   Reprint policy


《Two Sum》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Contiguous Array Contiguous Array
LeetCode Q 525 - Contiguous ArrayGiven a binary array, find the maximum length of a contiguous subarray with equal numbe
2019-04-17 Tong Shi
Next 
4Sum II 4Sum II
LeetCode Q 454 - 4Sum IIGiven four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are su
2019-04-17 Tong Shi
  TOC