美文网首页
两数之和

两数之和

作者: 有事没事扯扯淡 | 来源:发表于2019-03-29 11:01 被阅读0次

    最近突然奋发图强,想刷刷题,写个指南记录一下~

    题目描述:
    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    示例

    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    解析

    除了暴力法,可以利用哈希表!(一遍两遍都行)在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res;
            map<int,int> hash;
            map<int,int>::iterator it;
            int temp;
            for(int i=0;i<nums.size();i++)
            {
                temp = target-nums[i];
                it = hash.find(temp);
                if( it != hash.end())
                {
                    if(it->second != i)
                    {
                        res.push_back(it->second);
                        res.push_back(i);
                        break;
                    }       
                }       
                hash1.insert(pair<int,int>(nums[i],i));
            }     
            return res;            
        }
    };
    

    相关文章

      网友评论

          本文标题:两数之和

          本文链接:https://www.haomeiwen.com/subject/kxakbqtx.html