37,719
社区成员
发帖
与我相关
我的任务
分享
num = []
for (index,value) in enumerate(nums):
num.append((index,value))
numsSort = sorted(num,key=lambda x:x[1])
left = 0
right = len(numsSort)-1
sum = numsSort[left][1] + numsSort[right][1]
[code=python]class Solution(object):
def twoSum(self, nums, target):
#Use enumerate funtion to record the list which named nums
#index and value as a tuple
num = []
for (index,value) in enumerate(nums):
num.append((index,value))
numsSort = sorted(num,key=lambda x:x[1])
#index and sum the first and last number of the list
left = 0
right = len(numsSort)-1
sum = numsSort[left][1] + numsSort[right][1]
#Compare the value of sum and target
while(left < right):
if sum < target:
left += 1
sum = numsSort[left][1] + numsSort[right][1]
elif sum > target:
right -= 1
sum = numsSort[left][1] + numsSort[right][1]
elif sum == target:
return [numsSort[left][0],numsSort[right][0]]