1. Two Sum
LeetCode 1. Two Sum
Description
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]
Tags
Hash Table, Array
Solution
使用哈希表记录数字到下标的映射。遍历数组并检查target-num
是否在哈希表内,如果在则返回当前元素下标和哈希表查出的元素下标构成的元组,否则将当前数字和下标存入哈希表。
Use a hash table to record each element's value and its index. Iterate the array and look up the table if target-num
is already exists. If it exists, we have found a solution, which is a tuple composed of the index from the table and the current element's index, and return immediately.
Complexity
Time complexity:
Space complexity:
Code
func twoSum(nums []int, target int) []int {
m := map[int]int{} // num:index
for i, num := range nums {
if j, ok := m[target-num]; ok {
return []int{i, j}
}
m[num] = i
}
return nil
}
Last updated
Was this helpful?