題目連結(https://leetcode.com/problems/two-sum/description/)
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
*Follow-up: Can you come up with an algorithm that is less than O(n²) time complexity?
因爲此題是 sum 類題目基礎,而我對 unordered_map 以及雜湊表概念較為不熟,故選擇這題分享。
nums
和目標數字 target
。target
。如果陣列 nums 中有任兩個數相加等於目標值,就返回兩個數字的索引,比如說2+7=9,返回的並不是數字本身,而是數字對應的索引,第0、1位。而不能用同一個元素兩次,即使偶數目標值可以用兩個相同元素表達,但要有兩個相同元素使用。
nums = [2, 7, 11, 15], target = 9
-> 2 + 7 = 9
-> return [0, 1]
nums = [3,3], target = 6
-> return [0,1]
target
。給定一個重要變數:餘數,遍歷 nums 陣列,用目標值減去每一個數,並檢查 target - num
是否已經在雜湊表中:
時間複雜度:O(n)
空間複雜度:O(n)多設定一個有 n 個元素的 map(有key和value)
class Solution{
public:
vector<int> twoSum(vector<int>&nums, int target){
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){ //j從i+1開始才不會重復使用到同一個元素
int solution = nums[i] + nums[j];
if(target == solution)
return {i, j};
}
}
return {};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp; // key:數字, value:索引
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i]; // 差值(餘數)
if (mp.count(complement)) { // 如果差值已經出現過
return {mp[complement], i}; // 返回差值索引與當前索引
}
mp[nums[i]] = i; // 儲存當前數字及索引
}
return {}; // 理論上不會到這裡,因為題目保證一定有解
}
};
輸入:
nums = [2, 7, 11, 15], target = 9
mp
還沒有 7 → 存 2 的索引: mp = {2:0}mp
有 2 → 找到解,回傳索引值{0,1}輸入:
nums = [3, 3], target = 6
① unordered_map<int,int> mp;
unordered_map<key_type, value_type> name
要宣告兩個型別及 map 的名稱
key_type
= map 的 key,這裡是陣列中的數字(int)value_type
= key 對應的值,這裡是索引(int)② mp.count(complement)
③ mp[nums[i]] = i;
nums[i]
和它的索引 i
存進 map。④ return {mp[complement], i};
{}
建立一個 vector<int>
返回。return mp[complement], i;
)
return {mp[complement], i};
return mp[complement], i;
或 return i, mp[complement];
return {}
,只是防止編譯報錯。ps. 部分內容經 AI 協助整理