[LeetCode] Two Sum

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> &numbers, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        // 这么屌炸天的方法,一定要记住,深刻记住
       vector<int> result;
       map<int, int> mp;
       for(int i = 0; i < numbers.size(); i++) {
           if(mp[target - numbers[i]] > 0) {
               result.push_back(mp[target - numbers[i]]);
               result.push_back(i + 1);
           }
           else
               mp[numbers[i]] = i + 1;      // notices here
       }
       return result;
    }
};

原题:http://oj.leetcode.com/problems/two-sum/

posted on 2013-10-19 23:31  風逍遥  阅读(146)  评论(0编辑  收藏  举报

导航