标签:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::map<int, int> map; for(int i = 0; i < nums.size(); i++) { if(map.find(target - nums[i]) != map.end()) { std::vector<int> result{map[target - nums[i]], i + 1}; return result; } map[nums[i]] = i + 1; } } };
Python Code:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ map = {} for index,num in enumerate(nums): if target - num in map: return [map[target - num], index + 1] map[num] = index + 1
JS Code:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { var map = {} for(i = 0; i < nums.length; i++) { if(map.hasOwnProperty(target - nums[i])) { return [map[target - nums[i]], i + 1] } map[nums[i]] = i + 1 } };
标签:
原文地址:http://www.cnblogs.com/cxiaojia/p/5083605.html