您的位置:首页 > 其它

LeetCode 1. Two Sum (两数之和)

2017-07-11 20:24 323 查看

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

题目标签:Array

  这道题目给了我们一个target, 要我们从array里找到两个数相加之和等于这个target。

  可以利用暴力搜索,虽然可以通过, 但是速度太慢。

  这一题可以利用 HashMap 来把每一个数字的值 当做 key, 数字的index 当作 value 存入map;当遇到一个数字,就去map 检查一下, target - 这个数字 的值存不存在,有的话,就返回它们的index;没有的话,就把这个新的数字 存入map。

 

 

Java Solution:

Runtime beats 74.40% 

完成日期:03/09/2017

关键词:Array, HashMap

关键点:利用HashMap 保存每一个数字的 value 和 index, 对于每一个数字,去HashMap 查找 target - 当前数字的值。

 

public class Solution
{
public int[] twoSum(int[] nums, int target)
{
int [] res = new int[2];

HashMap<Integer, Integer> map = new HashMap<>();

for(int i=0; i<nums.length; i++)
{
// for this number, check map has target - this number or not
int temp = target - nums[i];
if(map.containsKey(temp))
{
res[0] = map.get(temp);
res[1] = i;
break;
}

// save this number into map
map.put(nums[i], i);

}

return res;
}
}

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: