LeetCode Two Sum
2014-04-15 10:59
411 查看
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]);
}
}
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]);
}
}
相关文章推荐
- 上班第一天
- 分手后还可以做朋友吗?
- vivado学习实验4笔记
- 深入理解Java内存模型《一》基础
- CSS3 transition 属性过渡效果 详解
- windows下命令行启动任意软件
- php的form中元素name属性相同时的取值问题
- 查询端口号占用问题
- 关于数据库容灾之数据容灾的总结
- 清软国际背景
- Flex应用程序转化为jsp程序—饼状图
- Java8初体验(二)Stream语法详解
- mac 单独安装gcc
- ActiveMQ入门实例
- 搭建属于你的在线实时采集系统——HTML5 在嵌入式系统中的应用
- Android菜鸟的成长笔记(11)——Android中的事件处理
- 基于Delphi的融合DLL中的窗口
- 数据挖掘模型介绍之四:最近邻方法和基于记忆的推理
- mac 单独安装gcc
- UML类图关系-转