Lintcode56 Two Sum solution 題解

【題目描述】

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.

Notice:You may assume that each input would have exactly one solution

給一個(gè)整數(shù)數(shù)組,找到兩個(gè)數(shù)使得他們的和等于一個(gè)給定的數(shù) target。你需要實(shí)現(xiàn)的函數(shù)twoSum需要返回這兩個(gè)數(shù)的下標(biāo), 并且第一個(gè)下標(biāo)小于第二個(gè)下標(biāo)。注意這里下標(biāo)的范圍是 1 到 n,不是以 0 開頭。

注意:你可以假設(shè)只有一組答案。

【題目鏈接】

www.lintcode.com/en/problem/two-sum/

【題目解析】

三種解法。

解法一, hash

從左往右掃描一遍,然后將數(shù)及坐標(biāo),存到map中。然后再掃描一遍即可。時(shí)間復(fù)雜度O(n)

解法二,雙指針掃描

將數(shù)組排序,然后雙指針從前后往中間掃描。時(shí)間復(fù)雜度O(n*lgn)。因?yàn)槭且蠓祷卦瓟?shù)組的下標(biāo),所以在排序的時(shí)候還得有額外的數(shù)組來存儲(chǔ)下標(biāo)信息, 也挺麻煩。

解法三,暴力搜索

這個(gè)倒是最省事的。時(shí)間復(fù)雜度O(n*n)

【參考答案】

www.jiuzhang.com/solutions/two-sum/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容