LeetCode 1
阿新 • • 發佈:2018-09-01
大小 進行 for div ces 數據 assume pre vector
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].
Solution:
vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> temp; for(int i = 0; i < nums.size(); i++){ if(!temp.count(target - nums[i])){ if(!temp.count(nums[i])){ temp[nums[i]] = i; } }else{ return {temp[target - nums[i]], i}; } } return {}; }
PS.
用map的運行速度不快,應該用unordered_map。
map
map
是STL的一個關聯容器,它提供一對一(第一個為key
,每個key
只能在map
中出現一次,第二個為value
)的數據處理能力。map
內部自建一顆紅黑樹(一種非嚴格意義上的平衡二叉樹),所以在map
內部所有的數據都是有序的,且map
的查詢、插入、刪除操作的時間復雜度都是O(logN)
。在使用時,map
的key
需要定義operator<
。
unordered_map
unordered_map
和map
類似,都是存儲的key-value
的值,可以通過key
快速索引到value
。不同的是unordered_map
不會根據key
的大小進行排序,存儲時是根據key
的hash
值判斷元素是否相同,即unordered_map
內部元素是無序的。unordered_map
的key
需要定義hash_value
函數並且重載operator==
。
unordered_map
的底層是一個防冗余的哈希表(采用除留余數法)。哈希表最大的優點,就是把數據的存儲和查找消耗的時間大大降低,時間復雜度為O(1)
;而代價僅僅是消耗比較多的內存。
LeetCode 1