首页 > 代码库 > Two Sum

Two Sum

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

开始想用双重循环,时间复杂度为O(N^2)超时,后面看到有人用Hashmap,利用了hashmap查找时间为常数的有点,降低了时间复杂度

参考:http://blog.csdn.net/jiadebin890724/article/details/23305449

 1 import java.util.Hashtable; 2 public class Solution { 3     public int[] twoSum(int[] numbers, int target) { 4         int result[] = new int[2]; 5  6         Hashtable<Integer, Integer> nums = new Hashtable<Integer, Integer>(); 7          8         for(int i = 0; i < numbers.length; i++){ 9             Integer index = nums.get(numbers[i]);10             if(null == index){11                 nums.put(numbers[i], i);12             }13             index = nums.get(target - numbers[i]);14             if(null != index && index < i){15                 result[0] = index + 1;16                 result[1] = i + 1;17                 break;18             }19         }        20         return result;21     }22 }

 

Two Sum