赞
踩
C++ Code:
- 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
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。