leetcode:Two Sum

来源:互联网 发布:用spss怎么输入数据 编辑:程序博客网 时间:2024/04/29 09:16

1. 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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
C++ Version:

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


Python Version:

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        if len(nums) <= 1:            return False        buff_dict = {}        for i in range(len(nums)):            if nums[i] in buff_dict:                return [buff_dict[nums[i]], i]            else:                buff_dict[target - nums[i]] = i


0 0
原创粉丝点击