zoukankan      html  css  js  c++  java
  • python3的leetcode题,两个数求和等于目标值,返回这两个数的索引组成的列表(三种方法)

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为gai目标值的 两个 整数。

    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9
    
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    # @Time    : 2018/11/17/017 22:17
    # @Author  : BenjaminYang
    # @FileName: twosum.py
    # @Software: PyCharm
    # @Blog    :http://cnblogs.com/benjamin77
    
    
    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            # 方法一:太抽象难以理解
            '''
           for index, value in enumerate(nums):
              next_index=index+1
              if target - value in nums[next_index:]:
           return [index,nums[next_index:].index(target-value)+next_index+1]
            '''
    
    
            # 方法二:使用双层for循环 效率较低但是易于理解
            '''
            result=[]
            for i in range(len(nums)):
                for j in range(i+1,len(nums)):
                    if target==nums[i]+nums[j]:
                        result.append(i)
                        result.append(j)
                    return result
            '''
            # 方法三:
            # 一次循环求差,然后在给定的list中寻找是否有相同值出现,求其index。
    
            # 有一个小技巧是可以先用x代替原始元素。
    
            # 只需要一次循环就可完成,在时间复杂度上优于第一种算法。
            result=[]
            nums_1=nums.copy() #浅拷贝
            i=0
            while len(nums)>0:
                pop=nums.pop(0) #弹出列表的第一个元素
                jj=nums_1[i] #jj对应的值为index为0-3的值
                nums_1[i]='x'
    
                if target - pop in nums_1:
                    next_index=nums_1.index(target - pop) #如果targe-下一个目标值不为零 就将列表的第一个索引赋值给next_index
                    if i !=next_index:  #如果弹出后的第一个索引不等于下一个目标索引就可以认定 这两个索引就是目标索引
                        result.append(i)
                        result.append(next_index)
                        break
                    nums_1[i]=jj #   #如果不满足条件就将原始值赋给第一位
                    i+=1  #每次循环初始索引加1
    
    
            return result
    nums = [2, 7, 11, 15]
    s = Solution()
    target = 9
    print(s.twoSum(nums, target))
  • 相关阅读:
    firefox native extension -- har export trigger
    配置jenkins slave 问题,ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.
    尝试用selenium+appium运行一个简单的demo报错:could not get xcode version. /Library/Developer/Info.plist doest not exist on disk
    ruby 除法运算
    ERB预处理ruby代码
    ruby self.included用法
    ruby include和exclude区别
    symfony安装使用
    解决git中文乱码
    读《微软的软件测试之道》有感(上)
  • 原文地址:https://www.cnblogs.com/benjamin77/p/9980564.html
Copyright © 2011-2022 走看看