zoukankan      html  css  js  c++  java
  • [LeetCode]题1:two sum

     

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    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.

     这道题穷举法时间复杂度o(n2)太高了,通过转换为减法利用字典查找数字可以更快的完成。字典初始化和查找可合并成一个循环。另一种想法是对给定数组进行排序,首尾不断相加,直到找到指定的和。

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict={}
            for i , num in enumerate(nums):
                if(target-num)in dict:
                    return(dict[target-num],i)
                else:
                    dict[num] = i



  • 相关阅读:
    kafka 启动停止
    kafka消息长度限制
    python给回调函数传参数
    Promise封装setTimeout
    Twisted 基础
    kafka-eagle
    go安装
    python asyncio
    ajv参数验证
    sequlizejs学习笔记整理
  • 原文地址:https://www.cnblogs.com/a-little-v/p/9261180.html
Copyright © 2011-2022 走看看