Leetcode001. Two Sum

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode001. Two Sum相关的知识,希望对你有一定的参考价值。

题目:

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 sameelement twice.

Example:

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

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

题解:

Solution 1 (my submmision)

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

Solution 2

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

相当于建立数组中每个元素的相对应的加数的集合,这个加数对应了原数组中元素的坐标。

 

以上是关于Leetcode001. Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode001. Two Sum

LeetCode刷题记录001Two Sum

LeetCode 001 Two Sum - Java

LeetCode OJ_题解(python):001-Two Sum ArrayEasy

LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

LeetCode 第 371 题 (Sum of Two Integers)