Two Sum
2014-10-04 00:00
99 查看
摘要: Given an array of integers, find two numbers such that they add up to a specific target number.
题目:
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
根据题目要求,在一个数组中找出两个数,使它们之和等于target。
解法1:
因为不知道数组是否有序,首先对数组进行排序,然后参照快排从数组首尾遍历,以找出这两个数,但考虑到一个较好排序的平均时间复杂度为O(nlogn),比较费时,所以采用解法2.
解法2:
本解法需要一个map来存放数组中的值以及其所对应的索引值,使其能够一边查找一边放入,从而在O(n)内可完成,下面给出代码:
题目:
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
根据题目要求,在一个数组中找出两个数,使它们之和等于target。
解法1:
因为不知道数组是否有序,首先对数组进行排序,然后参照快排从数组首尾遍历,以找出这两个数,但考虑到一个较好排序的平均时间复杂度为O(nlogn),比较费时,所以采用解法2.
解法2:
本解法需要一个map来存放数组中的值以及其所对应的索引值,使其能够一边查找一边放入,从而在O(n)内可完成,下面给出代码:
import java.util.HashMap; public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) { // 一边查找,一边放入 if(map.get(target - numbers[i]) != null) { result[0] = map.get(target - numbers[i]) + 1; result[1] = i + 1; break; } else { map.put(numbers[i], i); } } return result; } }
相关文章推荐
- leetcode 46: Two Sum
- leetcode two sum
- leetcode之Two Sum
- [LeetCode] Two Sum
- Leetcode Two Sum
- two sum
- LeetCode-Two Sum
- Two Sum
- LeetCode1:Two Sum
- LeetCode-001 Two Sum
- [LeetCode] Two Sum [17]
- Two Sum
- LeetCode:two sum
- 【leetCode】Two Sum
- Two Sum
- Two sum
- leetcode-two sum
- LeetCode Two Sum
- Two Sum
- LeetCode 1:《Two Sum》