leetCode之 Two Sum
2016-02-25 17:50
344 查看
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.
Example:
Solution:
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(null == nums || nums.length < 2 ) {
return null;
}
int[] array = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
map.put(nums[i], i);
}
for(int i=0;i<nums.length;i++) {
int temp = target - nums[i];
if(null != map.get(temp) && map.get(temp) != i) {
array[0] = i;
array[1] = map.get(temp);
}
}
return array;
}
}
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution:
public class Solution {
public int[] twoSum(int[] nums, int target) {
if(null == nums || nums.length < 2 ) {
return null;
}
int[] array = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
map.put(nums[i], i);
}
for(int i=0;i<nums.length;i++) {
int temp = target - nums[i];
if(null != map.get(temp) && map.get(temp) != i) {
array[0] = i;
array[1] = map.get(temp);
}
}
return array;
}
}
相关文章推荐
- 关于ctags跟踪代码的总结
- 安装cdh
- 电脑硬件那点事(1)
- Java回调机制(以Android事件监听器为例)
- 高效Java编程工具集锦(转自极客头条)
- iOS Masonry用法
- svn中authz配置文件总结
- eclipse 和 android studio 快捷键对比
- idea 的问题
- spring的线程流程
- iOS单独创建xib详解
- win7下面安装python3.4+django1.7遇到的问题及解决
- 45.Which two statements are true about sequences created in a single instance database? (Choose two.
- java中把List转成json数组格式的字符串
- C- C&AI
- 在返回值为void的方法中如何中间截断运行
- python教程集合
- 自动安装与配置gitlab
- Android数据库框架-Archiver(LiteOrm)的使用
- 快速排序和插入排序