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       

    速度也明显提升:

  • 相关阅读:
    hdu 5170 GTY's math problem(水,,数学,,)
    hdu 5178 pairs(BC第一题,,方法不止一种,,我用lower_bound那种。。。)
    hdu 5179 beautiful number(构造,,,,)
    cf12E Start of the season(构造,,,)
    cf12D Ball(MAP,排序,贪心思想)
    cf 12C Fruits(贪心【简单数学】)
    cf 12B Correct Solution?(贪心)
    hdu 5171 GTY's birthday gift(数学,矩阵快速幂)
    hdu 5172 GTY's gay friends(线段树最值)
    cf 11D A Simple Task(状压DP)
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5939139.html
Copyright © 2011-2022 走看看