【LeetCode 1 : Two Sum】

来源:互联网 发布:台湾淘宝跟大陆一样吗 编辑:程序博客网 时间:2024/06/15 12:11

Description:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

// 方法一:class Solution {public:    vector<int> twoSum(vector<int>& nums, int target)     {        map<int, int> m;        int sz = nums.size();        for(int i = 0; i < sz; ++i)        {            map<int, int>::iterator p = m.find(target - nums[i]);            if(p != m.end())             {                vector<int> ret;                ret.push_back(p->second+1);                ret.push_back(i+1);                return ret;            }            m[nums[i]] = i;        }    }};
// 方法二:class Solution {public:    vector<int> twoSum(vector<int>& nums, int target)     {        unordered_map<int, int> mapping;        vector<int> result;        for(int i = 0; i < nums.size(); i++)        {            mapping[nums[i]] = i;        }        for(int i = 0; i < nums.size(); i++)        {            const int gap = target - nums[i];            if(mapping.find(gap) != mapping.end())            {                result.push_back(i+1);                result.push_back(mapping[gap] + 1);                break;            }        }        return result;    }};

小结:
使用Hash表,进行存储相应的键值对,这种方法会常用;

0 0
原创粉丝点击