1-Two Sum

问题描述:

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;

你可能感兴趣的:(SUM)