暴力法
class Solution:
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i,j]
排序之后两端搜索
class Solution:
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
new_num = sorted(nums)
i = 0
j = len(nums) - 1
while i < j :
if new_num[i]+new_num[j] == target:
break
if new_num[i]+new_num[j] < target:
i = i + 1
if new_num[i]+new_num[j] > target:
j = j - 1
for x in range(0, len(nums)):
if nums[x] == new_num[i]:
for y in range( 0, len(nums)):
if y == x:
continue
if nums[y] == new_num[j]:
if x > y :
return [y, x]
else:
return [x, y]
当然,暴力法的时间复杂度是n的平方,排序是nlogn,如果建立一个哈希表的话,应该会更快一点,毕竟底层实现不同