• 1. 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.

    Example:

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

    UPDATE (2016/2/13):
    The return format had been changed to zero-based indices. Please read the above updated description carefully.

    代码:

    LeetCode第一题,今天回国偷来做一下,还是蛮有意思的。

    乍一看这个题,当然遍历两遍,稳稳找出结果:

     """遍历两边找出来,时间复杂度O(N^2)"""
        def twoSum(self, nums, target):
            for i in nums:
                for j in range(nums.index(i)+1,len(nums)):
                    if(i + nums[j] == target):
                        return [nums.index(i),j]

    结果运行的好慢哦:

    还好用的是python,网上查了下,java这样写全都报超时错误,时间复杂度太高。

    于是,遍历一遍,在剩余列表中找到第二个元素即可:

     """遍历一遍找出来,时间复杂度O(N)"""
        def twoSum2(self, nums, target):
                for i in nums:
                    try:
                        #找出第二个元素是否存在,存在返回位置,从当前元素下一位开始找,避免重复
                        j = nums[nums.index(i)+1:].index(target - i)+nums.index(i)+1
                        return [nums.index(i),j]                      
                    except:
                        continue

    明显快多啦:)

    网上有查了下,居然没有想到python的字典,发现用列表写好蠢啊,哎~~~还是要多练习!

    边找边存入字典:

    """用字典实现,时间复杂度O(N)"""
        def twoSum3(self, nums, target):
            dict = {}
            for i in range(len(nums)):
                x = nums[i]
                #判断第二个元素的值是否存在在字典中
                if target-x in dict:
                    return (dict[target-x], i)
                #将元素按照{key:index}方式存入字典
                dict[x] = i       

    速度也明显提升:

  • 相关阅读:
    Python流程控制
    Python中的条件判断
    控制台出现“The script has an unsupported MIME type ('text/html')”报错
    React项目中使用hot-react-loader
    React组件绑定this的三种方法
    egg.js异步请求数据
    Zepto源码分析之二(新旧版本zepto.Z方法的区别)
    Zepto源码分析之一(代码结构及初始化)
    构建RN或Weex项目时,使用Android Studio常遇到的问题
    CentOS安装PHP7.*
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5939139.html
Copyright © 2020-2023  润新知