#1. Two Sum

上一篇 / 下一篇  2017-07-22 12:42:51 / 个人分类:leetcode

class Solution:
'''
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].
'''
def twoSum1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = list()
for x in range(len(nums)):
for y in range(x+1,len(nums)):
if nums[x]+nums[y] == target:
result.append((x,y))
return result[0]

def twoSum2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for x in range(len(nums)):
another = target - nums[x]
if another in nums:
if x != nums.index(another):
return x, nums.index(another)

aa = Solution()
print(aa.twoSum1([2, 7, 11, 15], 9))
print(aa.twoSum2([2, 7, 11, 15], 9))

TAG: leetcode

 

评分:0

我来说两句

Open Toolbar