zoukankan      html  css  js  c++  java
  • [剑指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.

  • 相关阅读:
    Linux系统负载
    full nat
    close wait 状态的随想
    记录一下 性能分析问题
    golang 反射
    socket里面那个又爱又恨的锁
    Difference between skbuff frags and frag_list
    浅析TCP协议---转载
    http 怎样关闭
    http 响应 ngx_http_send_header ngx_http_output_filter
  • 原文地址:https://www.cnblogs.com/wyz-2020/p/12425833.html
Copyright © 2011-2022 走看看