[LeetCode]Two Sum

Two Sum

这题思路很简单,创建一个hash table,用来存放访问过的数值和对应的位置。从头到尾循环,假如hash table里面有匹配的数值,则取出对应的数值的位置并直接返回。


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=9Output: 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.
        map<int, int> table;
        map<int, int>::iterator iter;
        vector<int> result;
        int comp;
        for (int i = 0;i < numbers.size();++i) {
            comp = target - numbers[i];
            iter = table.find(comp);
            if (iter == table.end()) {
                table.insert(pair<int, int>(numbers[i], i));
            } else {
                result.push_back(iter->second + 1);
                result.push_back(i + 1);
                return result;
            }
        }
        return result;
    }
};

你可能感兴趣的:(LeetCode,array,table,hash)