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 用键做下标来寻值
            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来寻值是常数级的,不用遍历;
② 注意map的寻值和插入方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,607评论 5 6
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,593评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • 这是一篇去年的小文,写父亲的。今天应景。父亲今年71岁了;今天应该来老家看看他去! 《我的父亲》 /剑鲁 父亲今年...
    剑庐阅读 3,068评论 0 0
  • 可能是日有所思 夜有所梦的原因,昨天晚上梦见了前男友。 梦里的我,坐在前男友和他的现任女友对面,愤懑,毒舌,用了所...
    EchoWalker阅读 2,224评论 0 1

友情链接更多精彩内容