LeetCode---TwoSum

来源:互联网 发布:mac铁锈红是chili吗 编辑:程序博客网 时间:2024/04/30 02:34


题目:

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


使用语言:C++

运行时间:36ms

代码:

class Solution{    public:        vector<int> twoSum(vector<int>& nums, int target) ;         Solution()=default;        ~Solution()=default;}; vector<int> Solution::twoSum(vector<int>& nums, int target)        {            map<int, int> temp; //储存结果            vector<int> indices(0) ; // 储存最终索引值                       int index1 = 1;   //索引值1            int index2 = 1;   //索引值2            int index_map = 1; // map索引值                       //将nums中的数存入map中作为key,再为每一个值赋予从1开始的连续value            for(vector<int>::iterator iter1 = nums.begin(); iter1!=nums.end(); ++iter1)              {                temp[(*iter1)] = index_map;                ++index_map;            }                        //用target减去nums中的元素,然后查找map中是否有对应的元素,如果有则保留index            for(vector<int>::iterator iter1 = nums.begin(); iter1!=nums.end(); ++iter1)            {                               if(temp.find(target-(*iter1))!=temp.end())                {                     if(temp[target-(*iter1)]==index1);                     else                      {                         index2 = temp[target-(*iter1)];                         break;                     }                }                ++index1;             }                        //将两个index存入另一个vector中,并返回            indices.push_back(index1);             indices.push_back(index2);            return indices;           }

 
0 0
原创粉丝点击