美文网首页
1. Two Sum

1. Two Sum

作者: 要上班的斌哥 | 来源:发表于2017-08-23 21:38 被阅读24次

    题目:

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

    解题思路:
    判断数组 nums 中是否存在 2 个数组元素之和等于给定的 target 的值

    1. 我们可以使用一个 map 来保存数组的信息,这个 map 的 key 是 nums 数组的元素值, value 是 nums 数组的索引
    2. 迭代数组 nums 的元素值,将 target 值减去 nums 数组的元素值,得到 taget - nums[i]
    3. 判断 map 中是否存在 key 为 taget - nums[i] 的 map,若是存在取出 key 为 taget - nums[i] 的值

    解题代码:

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> map;
        vector<int> retArray;
        for (int i = 0; i < nums.size(); i++) {
            map[nums[i]] = i;
        }
        for (int i = 0; i < nums.size() ; i++) {
            int value = target - nums[i];
            if (map.count(value) > 0 && map[value] != i) {
                retArray.push_back(i);
                retArray.push_back(map[value]);
                break;
            }
        }
        return retArray;
        }
    };
    

    参考

    1. https://leetcode.com/problems/two-sum/description/

    相关文章

      网友评论

          本文标题:1. Two Sum

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