[leetcode] Two Sum


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

tags: hash table, array

Leetcode的第一题,主要是熟悉一下STL下的Hash table的用法。

insert很简单,直接按照数组访问的方法,把key-value对插入unordered_map中即可。

查找比较tricky. hashMap.find(key)返回的是一个指向其中元素的迭代器,我们需要判断它是否等于hashMap.end(),如果相等的话,则key在哈希表中不存在,否则则存在。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int, int> hashMap;
        vector<int> re;
        for(int i = 0; i < numbers.size(); i++){
            hashMap[numbers[i]] = i;
        }
        for(int i = 0; i < numbers.size(); i++){
            int gap = target - numbers[i];
            auto it = hashMap.find(gap);
            if(it != hashMap.end() && hashMap[gap] > i){
                int j = hashMap[gap] + 1;
                i++;
                re.push_back(i);
                re.push_back(j);
                return re;
            }
        }
    }
};

Selection_003

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.