码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】001. Two Sum

时间:2017-09-02 22:35:15      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:span   class   集合   val   tco   two sum   not   style   push   

题目:

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;
    }
};

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

 

【Leetcode】001. Two Sum

标签:span   class   集合   val   tco   two sum   not   style   push   

原文地址:http://www.cnblogs.com/Atanisi/p/7467951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!