1 Two Sum 兩數(shù)之和
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].
題目描述:
給定一個整數(shù)數(shù)組 nums 和一個目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那兩個整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,你不能重復(fù)利用這個數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
- 暴力法: 對每個數(shù), 遍歷剩下的數(shù)求是否存在解. 時間復(fù)雜度O(n^2), 空間復(fù)雜度O(1)
- 一次遍歷哈希法: 建立一個map存放相應(yīng)元素對應(yīng)的目標(biāo)元素, 并在插入的時候檢查, 時間復(fù)雜度O(n), 空間復(fù)雜度O(n)
代碼:
C++:
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> result;
// key為nums的值, value為nums下標(biāo)
map<int, int> int_map;
for (int i = 0; i < nums.size(); i++)
{
// map.count()測試主鍵是否存在, 若存在返回1
if (int_map.count(nums[i]) != 0)
{
// push_back(elem)在容器最后位置添加一個元素elem
result.push_back(int_map[nums[i]]);
result.push_back(i);
break;
}
int_map[target- nums[i]] = i;
}
return result;
}
};
Java:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
result[0] = map.get(complement);
result[1] = i;
return result;
}
map.put(nums[i], i);
}
return result;
}
}
Python:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for index, num in enumerate(nums):
complement = target - num
if complement in dic:
return [dic[complement], index]
dic[num] = index