LeetCode #1 Two Sum

来源:互联网 发布:免费翻墙安卓软件 编辑:程序博客网 时间:2024/06/06 08:34

Description

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


Analysis

题目难度为:easy,实际上解决方法也十分简单,可以单纯使用数组来解决,两次遍历所给数组

for(i=0; i<nums.size(); ++i)    for (j = i+1; j<nums.size(); ++j)        if (nums[i]+nums[j] == target)            return vector<int> res(i,j)

当然,本题中没有使用这种方法,但是思想是一样的,使用了c++11中新提供的unordered_map数据结构来实现,具体代码如下所示。


Code(c++)

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> index;        vector<int> output;        for (int i = 0; i < nums.size(); ++i) {            int temp = target - nums[i];            if (index.find(temp) != index.end()) {                output.push_back(index[temp]);                output.push_back(i);                return output;            }            index[nums[i]] = i;        }        return output;    }};
0 0
原创粉丝点击