NC61 两数之和(python)
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f?tpId=188&&tqId=37022&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking
题目描述
给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:
给出的数组为 {20, 70, 110, 150},目标值为90
输出 index1=1, index2=2
示例1
输入: [3,2,4],6
返回值: [2,3]
# # # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # 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: return [i+1, j+1]
或者:
# # # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # class Solution: def twoSum(self , numbers , target ): # write code here dict = {} for index, value in enumerate(numbers): if target - value in dict: return [dict[target-value]+1, index+1] else: dict[value] = index #dict按照key由小到大排列
日行一善, 日写一撰