码迷,mamicode.com
首页 > 其他好文 > 详细

两数之和

时间:2021-02-22 12:03:28      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:auto   twosum   两数之和   turn   htable   答案   tab   rgb   col   

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

 

1、暴力解法

#include <vector>
#include <iostream>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int> &nums, int target) {
        int i,j;
        for (i = 0; i < nums.size() - 1; ++i) {
            for (j = i + 1; j < nums.size(); ++j) {
                if (nums[i] + nums[j] == target)
                    return {i,j};
            }
        }
        return {0,0};
    }
};

int main() {
    vector<int> nums{2, 7, 11, 15};
    Solution s;
    vector<int> res = s.twoSum(nums, 9);
    cout << res[0] << endl;
    cout << res[1] << endl;
}

 

2、哈希表

#include <vector>
#include <iostream>
#include <unordered_map>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
};


int main() {
    vector<int> nums{2, 7, 11, 15};
    Solution s;
    vector<int> res = s.twoSum(nums, 9);
    cout << res[0] << endl;
    cout << res[1] << endl;
}

 

两数之和

标签:auto   twosum   两数之和   turn   htable   答案   tab   rgb   col   

原文地址:https://www.cnblogs.com/zhangzhangtabszj/p/14422925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!