Two Sum

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 zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (hashMap.containsKey(numbers[i])) {
result[0] = hashMap.get(numbers[i]) + 1;
result[1] = i + 1;
return result;
}
else {
hashMap.put(target - numbers[i], i);
}
}
return null;
}

}
• 本文已收录于以下专栏：

Two Sum算法调试小demo

• 2017年08月17日 18:01
• 833B
• 下载

Two Sum leetcode c++

• 2015年10月01日 10:47
• 763B
• 下载

leetcode

#1 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number. The...

【Leetcode】1. Two Sum

1. Two Sum Total Accepted: 254411Total Submissions: 1031847Difficulty: Easy Given an array...

29. Divide Two Integers/49. Group Anagrams/96. Unique Binary Search Trees/560. Subarray Sum Equals K

Divide Two Integers Problem Description Implementation29. Divide Two IntegersProblem DescriptionDivi...

DAY1：leetcode #1 Two Sum

1、Two Sum Given an array of integers, return indices of the two numbers such that they add up to a...

Leetcode-1 Two Sum(Java) -by zzy

Problems: Given an array of integers, find two numbers such that they add up to a specific target n...

举报原因： 您举报文章：Two Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)