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

    速度也明显提升:

  • 相关阅读:
    函数的调用过程
    Android基础-弹出式菜单
    Android基础-上下文菜单(Content_Menu)
    Adnroid基础-选项菜单(OptionMenu)
    Android基础-UI界面(项目实战 点菜界面) 1.EditText 2.SeekBar 3.CheckBox 4.ToggleButton 5.RadioGroup 6.Button 7.TextView 8.ImageView
    Android基础-进度条(SeekBar)
    Android基础-开关按钮(ToggleButton)
    Android基础-单选框(RadioButton)
    显示应用名称
    在Xcode中使用pch文件
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5939139.html
Copyright © 2011-2022 走看看