码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-03-06 12:41:24      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:The   mission   time   number   连续   ret   off   索引   index   

[剑指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的连续正数序列

标签:The   mission   time   number   连续   ret   off   索引   index   

原文地址:https://www.cnblogs.com/wyz-2020/p/12425833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!