Two Sum
2014-12-16 10:39
197 查看
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
import java.util.Hashtable; public class Solution { public int[] twoSum(int[] numbers, int target) { int result[] = new int[2]; Hashtable<Integer, Integer> nums = new Hashtable<Integer, Integer>(); for(int i = 0; i < numbers.length; i++){ Integer index = nums.get(numbers[i]); if(null == index){ nums.put(numbers[i], i); } index = nums.get(target - numbers[i]); if(null != index && index < i){ result[0] = index + 1; result[1] = i + 1; break; } } return result; } }
相关文章推荐
- Two Sum
- [LeetCode OJ] Two Sum
- two sum 3道题
- [Leetcode] 1. Two Sum
- leetcode-1 two sum
- Java 哈希表运用-LeetCode 1 Two Sum
- LeetCode 1 Two Sum
- 1 Two Sum
- Two Sum
- LeetCode OJ 第1题 Two Sum 解题报告
- Leetcode 01 Two Sum
- [leedcode 01] Two Sum
- LeetCode 1: Two Sum
- Two Sum
- [LeetCode]Two Sum
- Leetcode -- Two Sum
- Two Sum
- LeetCode---Two Sum
- LeetCode 1:Two Sum
- Two Sum