Two Sum

来源:互联网 发布:家用菜刀 知乎 编辑:程序博客网 时间:2024/06/06 10:06

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.

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int index;        vector<int> result;        map<int, int> map;        for( index = 0; index < nums.size(); index++ )        {            if( !map.count( nums[index] ) )                map.insert(pair<int, int> (nums[index], index) );            if( map.count( target - nums[index] ) )            {                int n = map[ target - nums[index] ];                if( n < index)                {                    result.push_back( n );                    result.push_back( index );                }            }       }       return result;    }};
0 0
原创粉丝点击