美文网首页
1. 两数之和

1. 两数之和

作者: coconutyao | 来源:发表于2018-03-29 11:50 被阅读0次

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>();
    }
};

相关文章

  • 1. 两数之和

    https://leetcode-cn.com/problems/two-sum/description/给定一个...

  • 1. 两数之和

    内容 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素...

  • 1. 两数之和

    20180919-摘抄自1. 两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每...

  • 1. 两数之和

    1、暴力法,求target-num[current]是否满足 2、哈希表

  • 1. 两数之和

    代码 分析 主要是利用map集合来存储值,存储的是下一下要找的值和当前的索引,然后找到的时候就可以知道这两个索引

  • 1. 两数之和

    一、题目原型: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同...

  • 1.两数之和

    题目: 给定一个整数数列,找出其中和为特定值的那两个数。 你可以假设每个输入都只会有一种答案,同样的元素不能被重用...

  • 1.两数之和

    leetcode算法学习,打算每日1篇 自己写的代码太low就不上了,主要是对最优代码的注释和自己的小小理解 题目...

  • 1. 两数之和

    LeetCode 的算法题 PHP解法记录 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假...

  • 1. 两数之和

    https://leetcode-cn.com/problems/two-sum/description/给定一个...

网友评论

      本文标题:1. 两数之和

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