1. Two Sum

作者: 美不胜收oo | 来源:发表于2018-09-13 18:27 被阅读0次

描述

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

思路一

由于数组中只有唯一一对符合目标的索引,故我们可以采用双重循环解决,时间复杂度O(n^2)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret;
        for(int i = 0;i<nums.size()-1;i++)
        {
            for(int j = i+1;j<nums.size();j++)
            {
                if(nums[i]+nums[j]==target)
                {
                    ret.push_back(i);
                    ret.push_back(j);
                    break;
                }
            }
        }
        return ret;
        
    }
};

思路二

我们采用map数据结构,定义当前索引为i,那么当前元素为nums[i]。我们试图在map里边找一个元素numTofind(numTofind = target - nums[i]),找到了返回map[numTofind]值即可。可以做以下思考,当找到满足 ?+ ?= target 的第一个元素的时候,他是被放进map中去的,当找到第二个元素的时候,才把第一个元素取出。连同第二个元素放入到vector中。时间复杂度为O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> hash;
        vector<int> res;
        int numTofind;
        for(int i=0;i<nums.size();i++)
        {
            numTofind = target - nums[i];
            //hash中找到了唯一一对中的前一个元素,两个元素分别进入vector
            if(hash.find(numTofind)!=hash.end())
            {
                res.push_back(hash[numTofind]);
                res.push_back(i);
                break;
            }
            //hash没有找到,保存到hash中
            hash[nums[i]] = i;
        }
        return res;
        
    }
};

不好理解运行过程的话,手动模拟一下样例即可。

相关文章

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 1. Two Sum

    1. Two Sum 题目:https://leetcode.com/problems/two-sum/ 难度: ...

  • leetcode hot100

    1. Two Sum[https://leetcode-cn.com/problems/two-sum/] 字典(...

  • leetCode #1

    #1. Two Sum

  • 1. Two Sum

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Description Given an array of integers, return indices of...

  • 1. Two Sum

    Problem Given an array of integers, return indices of the...

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Leetcode: 1. Two SumGiven an array of integers, return in...

网友评论

    本文标题:1. Two Sum

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