Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
此题目实际考察的为哈希表的使用,遍历数组的时候,将已经遍历过的元素放进哈希表(key为数组元素,value为数组索引)。这样在遍历到 nums[i] 时,判断一下哈希表中是否存在 target-nums[i] 即可。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
Java实现
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i ++) {
int t = target-nums[i];
if (map.containsKey(t)) {
return new int[] {map.get(t), i};
}
map.put(nums[i], i);
}
return null;
}
}
Python实现
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i in range(len(nums)):
t = target - nums[i]
if map.get(t) is not None:
return [map.get(t), i]
map[nums[i]] = i
Scala实现
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
var map = Map[Int, Int]()
var t = 0
for (i <- Range(0,nums.length)) {
t = target - nums(i)
if (map.contains(t)) {
return Array(map(t), i)
}
map += nums(i) -> i
}
return null
}
}