天天看點

1. Two Sum (Easy)

1. Two Sum

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hash;
        vector<int> result;        
        for (vector<int>::size_type index = ; index != nums.size(); ++index) {
            auto it = hash.find(target - nums[index]);
            if (it != hash.end()) {
                result.push_back(it->second);
                result.push_back(index);
                break;
            }
            hash[nums[index]] = index;
        }
        return result;       
    }
};
           

本題的思想是用哈希容器map存儲資料及其下标,因為map的find()複雜度為O(1),

是以整個程式的複雜度為O(n)。