散列寻找

class Solution {
public:
    /**
     * 
     * @param numbers int整型vector 
     * @param target int整型 
     * @return int整型vector
     */
    vector<int> twoSum(vector<int>& numbers, int target) {
        // write code here
        int n = numbers.size();
        vector<int> ans(2, 0);
        unordered_map<int, int> mp;
        for (int i = 0; i < n; ++i) {
            if (mp.find(numbers[i]) == mp.end()) { // 哈希表中没有当前值
                mp[target - numbers[i]] = i+1;   // 将目标值与当前值的差值作为哈希值, 保存当前值的下标
            }
            else {  // 当前值在哈希表中
                ans[0] = mp[numbers[i]];
                ans[1] = i+1;
                return ans;  // 返回两数下标
            }
        }
        return ans;
    }
};