力扣 1.两数之和

题目链接:https://leetcode-cn.com/problems/two-sum

方法一、暴力求解:两层循环

时间复杂度:O(n^2)

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        int n = nums.size();
        //两层循环直接求解
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
};

方法二、查找表法:unordered_map

时间复杂度:O(n)

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        std::unordered_map  map;
        for(int i = 0; i < nums.size(); i++){
            auto n = map.find(target - nums[i]);
            if(n != map.end()){
                return {n->second, i};
            }
            map.insert(pair(nums[i],i));
        }
        return {};
    }
};

你可能感兴趣的:(力扣)