LeetCode1 两数之和

47 阅读1分钟

LeetCode1 Two Sum

Given an array of integers and an integer , return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

暴力搜索法

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = i + 1; j < nums.size(); ++j) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
};

时间复杂度:O(N2)O(N^2)

初学cpp注释:

  1. 定义了Solution类,类中有public类型的函数twoSum.
  2. vector<int>类似变长数组.
  3. vector的长度用.size()表示.
  4. &表示对对象的引用,不会复制nums,而是直接对nums进行操作.

哈希表

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashMap; 
        for (int i = 0; i < nums.size(); ++i) {
            int complement = target - nums[i];
            if (hashMap.count(complement)) {
                return {hashMap[complement], i};
            }
            hashMap[nums[i]] = i;
        }
        return {};
    }
};

时间复杂度:O(N)O(N)

初学cpp注释:

unordered_map是C++标准库提供的一个哈希表容器,用于以常数平均时间O(1)进行快速查找,插入和删除操作.功能类似于Python的字典(dict).

引入头文件:#include <unordered_map>

基本语法:unordered_map<KeyType, ValueType> myMap;,即unordered_map<键类型, 值类型> 名称

常用操作:

操作示例代码说明
插入元素map[key] = value;若 key 存在则更新,否则插入
查找元素map.count(key)map.find(key)判断 key 是否存在
获取值int val = map[key];获取 key 对应的值
遍历元素使用范围 for 循环遍历所有 key-value 对