美文网首页
LeeCode-01

LeeCode-01

作者: 浪淘沙008 | 来源:发表于2022-11-08 17:02 被阅读0次
vector<int> twoSum0(const vector<int>& 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<int> twoSum1(const vector<int>& nums, int target) {
    unordered_map<int, int> 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<int> arr = {2, 3, 4, 5, 6, 7, 7};
    vector<int> r = twoSum1(arr, 7);
    
    for (int i = 0; i < r.size(); i++) {
        cout << r.at(i) << endl;
    }
    return 0;
}

相关文章

网友评论

      本文标题:LeeCode-01

      本文链接:https://www.haomeiwen.com/subject/aqnwtdtx.html