两数之和 #
题目 #
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
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].
分析 #
使用 hash 表,记录过程数据,空间换时间
题解 #
func twoSum(nums []int, target int) []int {
tmp := make(map[int]int)
for k, v := range(nums) {
first, ok := tmp[v]
if ok {
return []int{first, k}
}
tmp[target - v] = k
}
return []int{}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap <Integer, Integer> tmp = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++) {
if (tmp.get(nums[i]) != null) {
return new int[] {tmp.get(nums[i]), i};
} else {
tmp.put(target - nums[i], i);
}
}
return new int[] {};
}
}
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
r = {}
for i in range(len(nums)):
if nums[i] in r:
return i, r[nums[i]]
else:
r[target - nums[i]] = i
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
叶王 © 2013-2024 版权所有。如果本文档对你有所帮助,可以请作者喝饮料。