1. 程式人生 > >LeetCode 1

LeetCode 1

大小 進行 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)。在使用時,mapkey需要定義operator<

unordered_map

unordered_mapmap類似,都是存儲的key-value的值,可以通過key快速索引到value。不同的是unordered_map不會根據key的大小進行排序,存儲時是根據keyhash值判斷元素是否相同,即unordered_map內部元素是無序的。unordered_mapkey需要定義hash_value函數並且重載operator==

unordered_map的底層是一個防冗余的哈希表(采用除留余數法)。哈希表最大的優點,就是把數據的存儲和查找消耗的時間大大降低,時間復雜度為O(1);而代價僅僅是消耗比較多的內存。

LeetCode 1