题目链接:传送门

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

题意:

给定一组数,其中有两个数满足相加之和为给定值,求这两个数的下标

思路:

(1) 暴力 O(\(n^2\))


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

(2) 用 map 标记

这里,看到Discuss里面用的是unordered_map,似乎更为合理,因此做了点改动

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

相关文章:

  • 2021-08-16
  • 2021-06-08
  • 2022-02-08
  • 2021-09-14
  • 2021-06-02
  • 2021-11-02
  • 2021-11-17
猜你喜欢
  • 2021-11-14
  • 2021-09-15
  • 2017-12-19
  • 2018-12-13
  • 2018-12-26
  • 2021-08-04
  • 2021-08-06
相关资源
相似解决方案