给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。
(注:返回的数组下标从1开始算起,保证target一定可以由数组里面2个数字相加得到)
数据范围:,,
要求:空间复杂度 ,时间复杂度
[3,2,4],6
[2,3]
因为 2+4=6 ,而 2的下标为2 , 4的下标为3 ,又因为 下标2 < 下标3 ,所以返回[2,3]
[20,70,110,150],90
[1,2]
20+70=90
class Solution: def twoSum(self , numbers , target ): # write code here passed =[] for i in range(len(numbers)): if target-numbers[i] in passed: return [passed.index(target-numbers[i])+1,i+1] else: passed.append(numbers[i]) return []从左往右依次检查数字是否满足答案,不满足的放入候选里和当前i进行比较
class Solution: def twoSum(self , n , t): # write code here l = len(n) d = {} for i in range(l): if n[i] in d: continue else: d[n[i]] = i for i in range(l): a = t-n[i] if (a in d) and d[a] != i: j = d[a] return [min(i, j)+1, max(i, j)+1] return -1
class Solution: def twoSum(self , numbers , target ): # write code here A = dict() for ii, val in enumerate(numbers): try: ii2 = A[target - val] return [min(ii,ii2)+1, max(ii,ii2)+1] except: A[val] = ii
class Solution: def twoSum(self , numbers , target ): # write code here hashmap = {} for i, num in enumerate(numbers): j = hashmap.get(num) if j is not None: return [j + 1, i + 1] diff = target - num hashmap[diff] = i
class Solution: def twoSum(self , numbers , target ): # write code here for i in range(len(numbers)): for j in range(i+1,len(numbers)): if numbers[i] + numbers[j] == target: list1 = [i+1,j+1] list1.sort() return list1 return []
# # # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # class Solution: def twoSum(self , numbers , target ): a=numbers.copy() numbers.sort() i,j=0,len(numbers)-1 while i<j: s=numbers[i]+numbers[j] if s>target: j-=1 elif s<target: i+=1 else: if numbers[i]==numbers[j]: k=numbers[i] ind=[j for j,x in enumerate(a) if x==k] return [ind[0]+1,ind[1]+1] else: res=[a.index(numbers[i])+1,a.index(numbers[j])+1] return res if res[0]<res[1] else res[::-1] return [] # write code here
# # 利用目标和减去其中一个值,在数组中遍历去寻找这个值 # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # class Solution: def twoSum(self , numbers , target ): # write code here if len(numbers)<2: return False length=len(numbers) for i in range(length-1): a=target-numbers[i] for j in range(i+1,length): if numbers[j]==a: return i+1,j+1 return None