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

Posted whiky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[剑指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.

以上是关于[剑指Offer]41 和为S的两个数字 VS 和为S的连续正数序列的主要内容,如果未能解决你的问题,请参考以下文章

剑指offer题目--面试中的各项能力章

剑指offer 42.和为S的两个数字

《剑指offer》JZ41 ~ JZ50

剑指offer---和为S的两个数字

《剑指offer》JZ41 ~ JZ50

《剑指offer》JZ41 ~ JZ50