LeetCode從零刷起 (1. Two Sum)

2017.3.27 刷題開(kāi)始

博主最近忙于找實(shí)習(xí),發(fā)現(xiàn)不少互聯(lián)網(wǎng)的大公司,在線筆試以及面試中都會(huì)考一些基本的編程題目,而LeetCode正是收集這些題目的一個(gè)平臺(tái),所以博主決定從零刷起,希望有興趣的小伙伴互相鼓勵(lì),共同進(jìn)步。
由于博主是博客小白,所以博客中的不成熟之處還請(qǐng)大家批判指正。LeetCode的刷題順序處于摸索狀態(tài),目前是按照題號(hào)從易到難。這種網(wǎng)上OJ也是第一次開(kāi)始刷,個(gè)人原創(chuàng)的算法中難免有不成熟之處,還希望大家多多指點(diǎn)。
閑話少說(shuō),直奔主題。

LeetCode(1.Two Sum)

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í)點(diǎn):
這道題應(yīng)用了hash表的知識(shí),具體用法可參見(jiàn) C++ Reference;此外,我注意到LeetCode對(duì)vevtor的使用也比較多,題主此前對(duì)vector這個(gè)數(shù)據(jù)結(jié)構(gòu)并不熟悉,所以此處也要強(qiáng)調(diào)一下,具體用法參見(jiàn)C++ Reference。

解題思路:
首先建立一個(gè)從int到int映射的hash表,將nums中的元素每一個(gè)都映射到hash表中。然后從頭開(kāi)始遍歷nums,查找目標(biāo)元素值是否在hash表中,如果沒(méi)有則繼續(xù)查找;如果有的話判斷一下兩個(gè)元素的下標(biāo)是否相同,避免出現(xiàn)下標(biāo)相同的情況。C++代碼如下:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> mapping;
        vector<int> ans;
        for (int i=0; i<nums.size(); ++i)
            mapping[nums[i]] = i;
        for (int i=0; i<nums.size(); ++i){
            int search = target - nums[i];
            if (mapping.find(search) != mapping.end() && mapping.at(search) != i){
                ans.push_back(i);
                ans.push_back(mapping.at(search));
                break;
            }
        }
        return ans;
    }
};

時(shí)間復(fù)雜度分析:
該算法時(shí)間復(fù)雜度為O(n)。建立hash表的時(shí)間復(fù)雜度為O(n);遍歷nums在hash表中查找的時(shí)間復(fù)雜度也為O(n)。所以,整個(gè)算法的時(shí)間復(fù)雜度為O(n)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容