首页 > 其他 > 详细

1-Two Sum

时间:2015-06-10 13:51:34      阅读:261      评论:0      收藏:0      [点我收藏+]

问题描述:

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

 

1)想都不用想,暴力破解    O(n2) runtime, O(1) space

 跑了460ms

技术分享
 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for (int i = 0; i < nums.length; i++) {
 4             for (int j = i + 1; j < nums.length; j++) {
 5                 if (nums[i] + nums[j] == target) {
 6                     int[] output = new int[] { i+1, j+1 };
 7                     return output;
 8                 }
 9             }
10         }
11         return null;
12     }
13 }
View Code

2)看了提示,使用hashtable  O(n) runtime, O(n) space

跑了404 ms

技术分享
 1 import java.util.Hashtable;
 2 public class Solution {
 3     public int[] twoSum(int[] nums, int target) {
 4         Hashtable<Integer, Integer> hashtable=new Hashtable<Integer, Integer>();
 5         for (int i = 0; i < nums.length; i++) {
 6             Integer one=hashtable.get(nums[i]);
 7             if(one==null)
 8                 hashtable.put(nums[i], i);
 9             Integer two=hashtable.get(target-nums[i]);
10             if(two!=null&&two<i)
11             {
12                 int[] output = new int[] { two+1, i+1 };
13                 return output;
14             }
15         }
16         return null;
17     }
18 }
View Code

3)既然hashtable可以,那么hashmap也行~

跑了368 ms

技术分享
 1 public class Solution {
 2 
 3     public int[] twoSum(int[] nums, int target) {
 4         HashMap<Integer, Integer> hashMap=new HashMap<Integer, Integer>();
 5         for (int i = 0; i < nums.length; i++) {
 6             Integer one=hashMap.get(nums[i]);
 7             if(one==null)
 8                 hashMap.put(nums[i], i);
 9             Integer two=hashMap.get(target-nums[i]);
10             if(two!=null&&two<i)
11             {
12                 int[] output = new int[] { two+1, i+1 };
13                 return output;
14             }
15         }
16         return null;
17     }
18 }
View Code

PS:HashTable实施了串行化,而HashMap没有实施,那么理所当然效率上面来说,HashTable的效率不如HashMap;

1-Two Sum

原文:http://www.cnblogs.com/AloneAli/p/4565687.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!