• 算法题


    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].

    给出一个数组和一个数,返回数组中能得出目标数的两个数的索引
    两种方法:
    一 循环两次

      
    class Solution1(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            n=len(nums)
            looktable={}
            if n>=2:
                for i,numi in enumerate(nums):
                    for j,numj in enumerate(nums[i+1:]):
                        if numj==target-numi:
                            return [i,i+1+j]
            else:
                print 'wrong data'
                return None
    

      




    二 循环一次,同时用一个词典记录访问过的元素
    class Solution2(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            n=len(nums)
            looktable={}
            if n>=2:
                for i,numi in enumerate(nums):
                    if target-numi in looktable:
                        return [i,looktable[target-numi]]
                    looktable[numi]=i
            else:
                print 'wrong data'
                return None
    

      

    nums=[1,2,1,3]
    target=2
    s=Solution2()
    print s.twoSum(nums,target)

    返回结果为第一种解决方案返回[0,2]

    第二种返回[2,0]

    可见第一种方案可以保持结果在原序列中的顺序,第二种方案可以把查找表那部分单独拿出来,这样事先把索引建好,就能保持结果的顺序

    class Solution2(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            n=len(nums)
            looktable={}
    
            if n>=2:
                for i,numi in enumerate(nums):
                    looktable[numi]=i
                for i,numi in enumerate(nums):
                    if target-numi in looktable:
                        return [i,looktable[target-numi]]
                    
            else:
                print 'wrong data'
                return None
    

      这样初期费时,但是第二次循环时结果会出来很快,因为如果第一个元素满足,则直接返回了。,典型拿空间换时间的策略。



  • 相关阅读:
    电子工程师的血泪史
    最简单的bootloader的编写步骤
    6811汇编语言
    Tiny6410SHT10温湿度传感器
    Tiny6410裸机程序
    无线收发模块NRF24LU1和NRF24LE1
    转载工作10年的人总结的6句话
    Tiny6410取模软件设置
    别人的感悟
    在Windows下用Virtualbox虚拟linux时共享文件夹设置的方法
  • 原文地址:https://www.cnblogs.com/xqnq2007/p/7486814.html
Copyright © 2020-2023  润新知