LeeCode-01

vector twoSum0(const vector& nums, int target) {
    for (int i = 0; i < nums.size(); i++) {
        int t = target - nums[i];
        for (int j = 0; j < nums.size(); j++) {
            if (nums.at(j) == t && j != i) {
                return {i, j};
            }
        }
    }
    return {};
};
// 将数字添加到字典中的时候顺带查找,空间复杂度O(n),时间复杂度O(1)
vector twoSum1(const vector& nums, int target) {
    unordered_map hashTable;
    for (int i = 0; i < nums.size(); i++) {
        auto it = hashTable.find(target - nums[i]);
        if (it != hashTable.end()) {
            return {it->second, i};
        }
        hashTable[nums[i]] = i;
    }
    return {};
}


int main(int argc, const char * argv[]) {
    
    vector arr = {2, 3, 4, 5, 6, 7, 7};
    vector r = twoSum1(arr, 7);
    
    for (int i = 0; i < r.size(); i++) {
        cout << r.at(i) << endl;
    }
    return 0;
}

你可能感兴趣的:(LeeCode-01)