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

給一個整數數組,找到兩個數使得他們的和等於一個給定的數 target。你需要實現的函數twoSum需要返回這兩個數的下標, 並且第一個下標小於第二個下標。注意這裏下標的範圍是 1 到 n,不是以 0 開頭。

注意:你可以假設只有一組答案。

【題目鏈接】

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

【題目解析】

三種解法。

解法一, hash

從左往右掃描一遍,然後將數及座標,存到map中。然後再掃描一遍即可。時間複雜度O(n)

解法二,雙指針掃描

將數組排序,然後雙指針從前後往中間掃描。時間複雜度O(n*lgn)。因爲是要求返回原數組的下標,所以在排序的時候還得有額外的數組來存儲下標信息, 也挺麻煩。

解法三,暴力搜索

這個倒是最省事的。時間複雜度O(n*n)

【參考答案】

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章