1. 两数之和

https://leetcode-cn.com/problems/two-sum/description/
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0,1].

主要思路:

  1. 使用hashmap存储每个数组元素相应下标<key=array_value, value=array_index>。
  2. 遍历数组,查找target - current_value是否已存在在hashmap中。存在则返回当前元素和在hashmap查到的元素相应下标,否则将<current_value, current_index>添加到hashmap。

代码实现:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashmap;
        for (size_t i = 0; i < nums.size(); ++i) {
            int current = nums[i];
            if (hashmap.find(target - current) != hashmap.end()) {
                vector<int> result;
                result.push_back(hashmap[target - current]);
                result.push_back(i);
                return result;
            } else {
                hashmap[current] = i;
            }
        }
        return vector<int>();
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容