初级算法题(1)

117 阅读1分钟

这是一个非常基础且广泛用于面试的问题

题目名称:Two Sum

题目描述:

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

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

示例

#include <vector>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    // Your code here
}

输入:

nums = [2, 7, 11, 15], target = 9

输出:

[0, 1]

解释:

因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

注意:

这个问题的关键在于,你需要找到一种方法,在遍历数组的同时记录已经遍历过的数字,这样可以在 O(n) 的时间复杂度内找到结果,其中 n 是数组的长度。

答案:

#include <iostream>
#include <vector>
#include  <unordered_map>
using  namespace std;

vector<int> twoSum(vector<int>& nums, int target) {   // 定义函数,接受一个整数向量和一个整数作为参数。
    unordered_map<int, int> hash;  // 创建一个哈希表,用于存储遍历过的元素和它们的索引。

    for (int i = 0; i < nums.size(); i++) {  // 遍历输入数组。
        int complement = target - nums[i];  // 计算目标值和当前元素的差值。

        if (hash.find(complement) != hash.end()) {  // 在哈希表中查找是否有元素等于差值。
            return {hash[complement], i};  // 如果有,返回这个元素的索引和当前元素的索引。
        }

        hash[nums[i]] = i;  // 如果没有找到,将当前元素和其索引添加到哈希表中。
    }

    return {};  // 如果遍历完整个数组都没有找到满足条件的元素,返回一个空的数组。
}

调用使用:

int main() {

    vector<int> nums = {2, 11, 7, 15};
    int target = 9;
    vector<int> result  = twoSum(nums,target);
    cout << "[" << result[0] << " ," << result[1] << "]" << endl;

    return 0;

}

打印如下:

[0,2]