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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

分析

刚看到题目,闪过脑子的第一个想法就是用两层循环进行相加判断,但是,提交之后,超时了。
然后想了好久不知道怎么解决,只能参考别人的代码,用了map,缩短了查找时间,同时改变了每个都相加在和target比对的办法,直接用target减去一个数,然后再找有没有对应的数。
map.count()返回某个元素出现的次数,不是0就是1,因为再map里面不存在等价的两个(以上)元素

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> results;
        
        map<int, int> map; 
        
        for(int i=0;i<nums.size();i++){
            if(!map.count(nums[i])){//不存在才将数添加进map,且用nums的values做key,key做values,方便呢之后通过相减的值来获取key
                map[nums[i]]=i;
            }
            if (map.count(target-nums[i])){
                int n=map[target-nums[i]];
                if (n<i){//防止出现自己加自己的情况 
                    results.push_back(map[target-nums[i]]);
                    results.push_back(i);
                    return results;//题目说只有一种情况,所以直接返回 
                } 
            } 
        } 
        
        return results;        
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容