LeetCode--Two Sum

来源:互联网 发布:js定义数组的方法 编辑:程序博客网 时间:2024/06/06 19:38

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

思路:用一个map存储数组的下标后,已知一个数以及两数之和,在表中查找另一个数,因为假设输入只有一个答案,所以下标交换没有意义。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        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++)        {            int gap=target-nums[i];            if(mapping.find(gap)!=mapping.end()&&mapping[gap]>i)            {                result.push_back(i);                result.push_back(mapping[gap]);                break;            }        }        return result;    }};