[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].


<br />

Method 1 Brute Force

The requirement is pretty simple and straightforward as we can just find out whether target - num[i] is the array or not; therefore, the simplest way is to Brute-Force this by iterating every possible value in the array.

And I will pass the code for this method for its low time-efficiency.
<br />

Method 2 HashTable

To achieve better time efficiency, we should use a hash table to store the array of integers in order to quickly find out the target number.

For every num[i], we have to find target - num[i] in the hash table, since the mechanism of storing numbers in hash table, we can reduce the look up time to from O(1) to O(n) instead of O(n^2).

Code are followed as below.

Java

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
           map.put(nums[i], i);
    }

    for (int i = 0; i < nums.length; i++) {
           int subside = target - nums[i];

           if (map.containsKey(subside) && map.get(subside) != i) {
                return new int[] { i, map.get(subside) };
           }
    }
    throw new IllegalArgumentException("No such solution");
}
Complexity Analysis

Time Complexity: O(n).
In fact, we have to go through all n numbers exactly twice to find the solution.
Space Complexity: O(n).
<br />

Method 3 One-pass Hash Table

The procedure to store every number into hash map is unnecessary as we can combine these two steps into one action. We can first look up in the current hash map to find whether the matched answer is already in the map, if not, then we can add the number into the hash map.

The code is only slightly changed from the code above.

Java

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        int subside = target - num[i];

        if (map.containsKey(subside)){
            return new int[] { map.get(subside), i };
        }
        else{
            map.put( num[i], i );
        }
    }
     throw new IllegalArgumentException("No such solution.");
}
Complexity Analysis

Time Complexity: O(n).
Space Complexity: O(n).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市缩麸,隨后出現(xiàn)的幾起案子虫溜,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件康栈,死亡現(xiàn)場(chǎng)離奇詭異辆苔,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)忿族,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門锣笨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蝌矛,“玉大人,你說我怎么就攤上這事错英∪肴觯” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵椭岩,是天一觀的道長(zhǎng)茅逮。 經(jīng)常有香客問我,道長(zhǎng)判哥,這世上最難降的妖魔是什么献雅? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮塌计,結(jié)果婚禮上挺身,老公的妹妹穿的比我還像新娘。我一直安慰自己锌仅,他們只是感情好章钾,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著热芹,像睡著了一般贱傀。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上伊脓,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天窍箍,我揣著相機(jī)與錄音,去河邊找鬼丽旅。 笑死椰棘,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的榄笙。 我是一名探鬼主播邪狞,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼茅撞!你這毒婦竟也來了帆卓?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤米丘,失蹤者是張志新(化名)和其女友劉穎剑令,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體拄查,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡吁津,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了堕扶。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片碍脏。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡梭依,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出典尾,到底是詐尸還是另有隱情役拴,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布钾埂,位于F島的核電站河闰,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏褥紫。R本人自食惡果不足惜淤击,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望故源。 院中可真熱鬧,春花似錦汞贸、人聲如沸绳军。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽门驾。三九已至,卻和暖如春多柑,著一層夾襖步出監(jiān)牢的瞬間奶是,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國打工竣灌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留聂沙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓初嘹,卻偏偏與公主長(zhǎng)得像及汉,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子屯烦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

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