Two Sum
2014-04-28 17:26
337 查看
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
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
if (ht.get(target - numbers[i]) != null) {
ret[0] = ht.get(target - numbers[i]) + 1;
ret[1] = i + 1;
} else {
ht.put(numbers[i], i);
}
}
return ret;
}
}
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
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
if (ht.get(target - numbers[i]) != null) {
ret[0] = ht.get(target - numbers[i]) + 1;
ret[1] = i + 1;
} else {
ht.put(numbers[i], i);
}
}
return ret;
}
}
相关文章推荐
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统
- java很神奇 用swing制作欢迎屏幕
- java自动生成验证码插件-kaptcha
- ITeye上“10个人,8个人不会解释这个问题”的帖子
- Java IO与NIO的一些文件拷贝测试
- Java反射随记
- Java简单字符串插值实现