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:
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
Last updated
Was this helpful?