题目链接:https://leetcode.com/problems/two-sum/description/
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 twoSum(self, nums, target): 72ms
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
def twoSum(self, nums, target): 68ms
for i in nums:
index0=nums.index(i)
nums[index0]='*'
if target-i in nums:
index1=nums.index(target-i)
return [index0,index1]
def twoSum(self, nums, target):##nums有重复值 36ms
for i in nums:
index0=nums.index(i)
nums[index0]='*'
if target-i in nums:
index1=nums.index(target-i)
return [index0,index1]
def twoSum1(self, nums, target):##不适合有重复值 36ms
nums_={}
for i in nums:
nums_[target-i]=nums.index(i)
for j in nums:
nums_.pop(target-j)
if j in nums_.keys():
index1=nums.index(j)
index2=nums_[j]
return [index1,index2]
如果是递增有序的数组,可以设置两个指针,分别从左端右端往中间移动
然后如果和大于target,右指针左移一位,如果小于则左指针右移一位,待和为target或者左右指针相同返回。