LeetCode 1. Two Sum (两数之和)

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 - 当前数字的值。

 

 1 public class Solution 
 2 {
 3     public int[] twoSum(int[] nums, int target) 
 4     {
 5         int [] res = new int[2];
 6         
 7         HashMap<Integer, Integer> map = new HashMap<>();
 8         
 9         for(int i=0; i<nums.length; i++)
10         {
11             // for this number, check map has target - this number or not
12             int temp = target - nums[i];
13             if(map.containsKey(temp))
14             {
15                 res[0] = map.get(temp);
16                 res[1] = i;
17                 break;
18             }
19             
20             // save this number into map
21             map.put(nums[i], i);
22             
23         }
24         
25         return res;
26     }
27 }

参考资料:N/A

 

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

 

posted @ 2017-07-11 20:24  Jimmy_Cheng  阅读(284)  评论(0编辑  收藏  举报