1. Two Sum

2016-05-12  本文已影响0人  白菜炖豆腐

题目

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;        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读