leetcode two sum

leetcode twoSum

给定一个整数数组,和一个目标值,找出数组中,和为目标值的两个数。
你可以假设每个输入只对应一种答案,并且同样的元素不被重复利用。

示例:
给定数组: nums=[2,7,11,15]
给定的目标值:target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1 ]
"""
python 解决方案 1
"""
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        r = []
        for n in nums:
            f = target - n
            if f in nums:
                r.append(nums.index(n))
                r.append(nums.index(f))
                return r
        return r

"""
python 解决方案2
"""
"""
enumerate 的使用
"""
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i, num in enumerate(nums):
            if target-num in d:
                return [d[num], i]
            d[num] = i
// C++ 解决方案

#include<vector>
#include<unordered_map>
#include<iostream>

// using namespace std;

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

int main(int argc, char* argv[]){
    std::vector<int> nums = {2, 7, 11, 15};
    int target = 9;
    Solution s;
    std::vector<int> res = s.twoSum(nums, target);
    if(!res.empty()){
        std::cout<<"[";
    }
    for(int i = 0; i < res.size(); ++i){
        std::cout<<res[i];
        if(!(i+1 == res.size())){
            std::cout<<", ";
        }
    }
    std::cout<<"]"<<std::endl;
}
/* javascript 解决方案 */
/**
* 两数之和
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/

var twoSum = function(nums, target){
    var a = [];
    for(var i = 0, len=nums.length; i < len; ++i){
        var tmp = target - nums[i];
        if (a[tmp] != undefined) return [a[tmp], i];
        a[tmp] = i;
    }
};

版权声明:除特别注明外,本站所有文章均为王晨曦个人站点原创

转载请注明:出处来自王晨曦个人站点 » leetcode two sum

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注