描述
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 same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的解决办法
遍历数组,求出目标数字与数组元素的差值diff,然后在数组中找到diff,返回其index
代码如下
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = ''
for index in range(len(nums)):
diff = target - nums[index]
for index_another in range(index+1, len(nums)):
if nums[index_another] == diff:
temp = index_another
return [index, temp]
return None
算法评估
Runtime: 3416 ms, faster than 28.78% of Python online submissions for Two Sum.
Memory Usage: 12.7 MB, less than 63.87% of Python online submissions for Two Sum.
参考算法
// python3
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
if target-nums[i] not in dict:
dict[nums[i]]=i
else:
return [dict[target-nums[i]],i]
// JavaScript
const twoSum = function(nums, target) {
const comp = {};
for(let i=0; i<nums.length; i++){
if(comp[nums[i] ]>=0){
return [ comp[nums[i] ] , i]
}
comp[target-nums[i]] = i
}
};
## 参考链接
转载自:[https://leetcode.com/problems/two-sum/](https://leetcode.com/problems/two-sum/)
网友评论