LeetCode | Two Sum
2014-04-07 22:40
281 查看
题目
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
分析
用哈希表保存已经遍历的数据即可。
代码
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
分析
用哈希表保存已经遍历的数据即可。
代码
import java.util.HashMap; public class TwoSum { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; ++i) { int remain = target - numbers[i]; if (map.containsKey(remain)) { return new int[] { map.get(remain), i + 1 }; } else { map.put(numbers[i], i + 1); } } return null; } }
相关文章推荐
- [leetcode]Two Sum
- LeetCode----Two Sum
- 【LeetCode】Two Sum
- LeetCode two sum
- 【leetcode】1. Two Sum
- [LeetCode]Two Sum
- Leetcode(4)-Two Sum
- python- leetcode - Two Sum
- LeetCode - Two Sum
- LeetCode No.1 Two Sum
- Leetcode Q1: Two Sum
- 【LeetCode】1. Two Sum
- [leetcode]:Two Sum
- 【LeetCode】2. Two Sum
- [array] leetCode-1-Two Sum-Easy
- LeetCode-1. Two Sum
- LeetCode 001 Two Sum
- Leetcode 1 Two Sum
- LeetCode刷题笔录 Two Sum
- 1---LeetCode【Two Sum】|C语言|总结