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
my solution:
import java.util.*;
public class Solution {
public int[] twoSum(int[] numbers, int target)
{
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < numbers.length ; i++)
{
if(map.containsKey(numbers[i]))
{
int index = map.get(numbers[i]);
result[0] = index + 1;
result[1] = i + 1;
}
else {
map.put(target - numbers[i], i);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] numbers = {2,7,11,15};
int target = 9;
Solution solution = new Solution();
int[] result = solution.twoSum(numbers,target);
for(int i = 0 ; i < result.length ; i++)
System.out.println(result[i]);
}
}
本文介绍了一个算法,用于在整数数组中找到两个数,使得它们的和等于指定的目标值。通过使用哈希映射,该算法可以在一次遍历后返回正确的索引。
153

被折叠的 条评论
为什么被折叠?



