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].
###method 1:
class Solution(object):
def twoSum(self, nums, target):
a=0
for i in nums:
# print 'i',i
b=0
for j in nums:
# print 'j',j
if i + j == target:
if a<b:
return [a,b]
b +=1
a += 1
###method 2:
class Solution(object):
def twoSum(self, nums, target):
i = 1
while i <= len(nums):
j=0
while j < i:
sums = nums[i] + nums[j]
if sums == target:
if i > j:
return [j,i]
else:
return [i,j]
j += 1
i += 1
本文介绍了一种经典的算法问题——寻找数组中两个数相加等于特定目标值的索引。提供了两种不同的实现方法,包括遍历数组进行比较的方法。
327

被折叠的 条评论
为什么被折叠?



