1 题外话
最近觉得还是应该提前为将来面试做一点准备,所以准备慢慢刷下leetcode,大约每天1题的速度,保证自己不生手。在写代码的同时,同时将自己的代码和思路贴到这里。本博客可能会在我的新浪微博@MebiuW 和 个人网站同步(www.zerodigeek.com),只是可能略微延后
2 原题
题目的意思大致就是给定一个数组nums,这个数组里面有一些整形的变量,并且给定一个target的数字,让你从nums数组里找出两个位置的数,他们的和正好为target。
特别注意的就是起始位置是0(虽然我觉得这不是常识么?)
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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
3解题思想
这题我选择的做法很简单,使用HashMap(HashTable)<数,位置>去做,我们遍历nums的每一个数i前,首先检查HashMap中有没有保存一个数正好等于target-nums[i],如果有的话那么就证明就是这两个位置,输出就好,而如果没有的话就把自己的数值和位置放入HashMap当中就好。
题目很简单,也第一次写,所以就这样了,有问题请联系我哦
4解题代码(Java)
public class Solution {
public int[] twoSum(int[] nums, int target) {
//使用哈希表保存已有的数据和位置,方便快速索引
HashMap<Integer,Integer> set=new HashMap<Integer,Integer> ();
int result[]=new int[2];
//第一个不用考虑直接放入
set.put(nums[0],0);
int reserve;
for(int i=1;i<nums.length;i++){
//对于给定的当前数,还需要和哪个数相加才行
reserve=target-nums[i];
//根据是否有这个数进行判断
if(set.containsKey(reserve)==false){
set.put(nums[i],i);
}
else{
result[0]=set.get(reserve);
result[1]=i;
break;
}
}
return result;
}
}