难度:Easy
链接:点击打开链接
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.
思路:
让你从一个数组中找出两个数,他们相加等于target,自然是可以用两个循环来做,但是这样复杂度会很高。
所以可以换一种方法:
先将数组排序,并用两个指针指向头尾,检验两个指针指向的值,相加如何,如果相等,返回结果(如果用的是index,需要再处理下,因为需要返回index,而排序已经打乱了原先的index,最开始的index事先复制一份,在复制的数组中找头尾指针指向的值,为防止结果是重复的两个数字,尾指针指向的值在复制的数组中要反向遍历)
如果是小于结果,头指针+1
如果是大于结果,尾指针-1
这样会不断逼近想找到的两个数字
代码:
class Solution:
def twoSum(self, nums, target):
store = copy.deepcopy(nums)
nums.sort()
front = 0
back = len(nums)-1
while (front < back):
if (nums[front] + nums[back] == target):
r = list(range(len(store)))
r.reverse()
back_index = 0
for x in r:
if (store[x] == nums[back]):
back_index = x
break
return [store.index(nums[front]),back_index]
elif nums[front] + nums[back] < target:
front = front+1
elif nums[front] + nums[back] > target:
back = back-1