1. 程式人生 > 實用技巧 >leetcode148two-sum

leetcode148two-sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input:numbers={2, 7, 11, 15}, target=9

Output:index1=1, index2=2

題目描述

給出一個整數陣列,請在陣列中找出兩個加起來等於目標值的數, 你給出的函式twoSum 需要返回這兩個數字的下標(index1,index2),需要滿足index1 小於index2.。注意:下標是從1開始的 假設給出的陣列中只存在唯一解 例如:

給出的陣列為 {2, 7, 11, 15},目標值為9
輸出 ndex1=1, index2=2

示例1

輸入

[3,2,4],6

輸出

[2,3]
//方法一 暴力

//方法二 C++版本的兩遍雜湊表(官方題解)
/*
通過以空間換取速度的方式,我們可以將查詢時間從 O(n) 降低到 O(1)。
C++版本的雜湊表演算法採用unordered_map。
*/
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
unordered_map<int,int> tmpmap;
int length = nums.size();
for(int i = 0;i < length;i++){
tmpmap[nums[i]] = i;
}
for (int i = 0; i < length; i++){
if(tmpmap.count(target - nums[i]) != 0 && tmpmap[target - nums[i]] != i){
//使用count,返回的是被查詢元素的個數。如果有,返回1;否則,返回0。
ans.push_back(i);
ans.push_back(tmpmap[target - nums[i]]);
break;
}
}
return ans;
}

//方法三 C++版本的一遍雜湊表(官方題解)
/*
事實證明,我們可以一次完成。在進行迭代並將元素插入到表中的同時,我們還會回過頭來檢查
表中是否已經存在當前元素所對應的目標元素。如果它存在,那我們已經找到了對應解,並立即將其返回。
*/
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
unordered_map<int,int> tmpmap;
int length = nums.size();
for (int i = 0; i < length; i++){
if(tmpmap.count(nums[i]) != 0){
ans.push_back(tmpmap[nums[i]]);
ans.push_back(i);
break;
}
tmpmap[target - nums[i]] = i;
}
return ans;
}
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
cache = {}
for index,num in enumerate(nums):
another_num = target-num
if another_num in cache:
return [cache[another_num],index]
cache[num]=index
return None