6. Two Sum FROM Leetcode

題目

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

頻度: 5

解題之法

class Solution {
public:

    vector<int> twoSum(vector<int>& nums, int target) {
    
        std::map<int, int> my_map;
        vector<int> result;
        
        for(int i = 0; i < nums.size(); i++) {
        
        int complement = target - nums[i];
        
        //if numberToFind is found in map, return them
        if(my_map.find(complement)!=my_map.end()){
            
            result.push_back(i);
            result.push_back(my_map[complement]);//map 用鍵做下標(biāo)來(lái)尋值
            return result;
        }
        //number was not found. Put it in the map.

        //my_map.insert(i,nums[i]);
        // or say 
        //my_map.insert(pair<int,int>(i,nums[i]));
        //my_map.insert(i, nums[i]);
        my_map.insert(pair<int, int>(nums[i], i));
    }

    return result;
}
};

分析

① 用map來(lái)尋值是常數(shù)級(jí)的,不用遍歷;
② 注意map的尋值和插入方法

最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,660評(píng)論 5 6
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,105評(píng)論 0 23
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評(píng)論 0 33
  • 這是一篇去年的小文,寫父親的。今天應(yīng)景。父親今年71歲了;今天應(yīng)該來(lái)老家看看他去! 《我的父親》 /劍魯 父親今年...
    劍廬閱讀 437評(píng)論 0 0
  • 可能是日有所思 夜有所夢(mèng)的原因,昨天晚上夢(mèng)見(jiàn)了前男友。 夢(mèng)里的我,坐在前男友和他的現(xiàn)任女友對(duì)面,憤懣,毒舌,用了所...
    EchoWalker閱讀 310評(píng)論 0 1

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