Leetcode01

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, 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].

Solution:

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

using namespace std;

// 时间复杂度: o(n)
// 时间复杂度: o(n)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {

        unordered_map<int,int> record;
        for( int i = 0; i < nums.size(); i++){

            int complement = target - nums[i];
        if ( record.find( complement ) != record.end() ){
            int res[2] = {i, record[complement]};
            return vector<int>(res, res+2);
        }

        record[nums[i]] = i;
        }

        throw invalid_argument("the input has no solution");
    }
};

总结: 这里只写了时间复杂度最低的一种解法,用了查找表(hashmap)的思路。要注意如果有两个相同的值,存入查找表时会覆盖掉一个。上面方法巧妙解决了这个问题。

猜你喜欢

转载自blog.csdn.net/hghggff/article/details/82390185