[剑指Offer]41.和为S的两个数字 VS 和为S的连续正数序列

时间:2023-03-09 08:16:34
[剑指Offer]41.和为S的两个数字 VS 和为S的连续正数序列

[剑指Offer]41 和为S的两个数字 VS 和为S的连续正数序列

Leetcode T1 Two Sum

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].

题目:给一个序列和一个目标值,返回相加等于目标值的序列中元素的索引。

思路:遍历序列,用i记录序列第一个值的索引,值记录为val。用diff = target - val(# val1 + val2 = target),查看diff索引。当diff != i 时,返回[i, diff的索引]。

代码

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
val = nums[i]
diff = target - val
if diff in nums and i != nums.index(diff):
return [i, nums.index(diff)]

提交结果

Runtime: 1204 ms, faster than 23.29% of Python3 online submissions for Two Sum.

Memory Usage: 13.8 MB, less than 69.77% of Python3 online submissions for Two Sum.