• leetcode_No.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, and you may not use the same element twice.

    翻译:

      给出一个数字列表和一个目标值(target),假设列表中有且仅有两个数相加等于目标值,我们要做的就是找到这两个数,并返回他们的索引值。

    举例:

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

    解答: 

    # 方法1:双层循环,面试不会通过,时间复杂度太高
    def twoSum_way1(self,nums,target):
        """
        :param nums: 整数列表
        :param target:目标值
        :return:result 索引值
        """
        result = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    result.append(i)
                    result.append(j)
                    return result
    
    #方法2:通过判断target与某一个元素的差值是否也在列表之中,类似方法1,同样是面试官不期望的回答
    def twoSum_way2(self,nums,target):
        """
        :param nums: 整数列表
        :param target:目标值
        :return:result 索引值
        """
        result = []
        for i in range(len(nums)):
            first_num = nums[i]
            second_num = target - first_num
            if second_num in nums:
                j = nums.index(second_num)
                if i != j:
                    result.append(i)
                    result.append(j)
                    return result
    

      

    #适合面试的方法:
    #方法3:通过创建字典,将nums里的值和序号对应起来,
    # 并创建另一个字典存储目标值(Target)-nums的值,
    # 通过判断该值是否在nums内进行判断并返回其对应索引值
    class Solution:
        def twoSum_way3(self, nums, target):
            """
            :param nums: 整数列表
            :param target:目标值
            :return:result 索引值
            """
            #创建第一个字典:用于存储整数列表nums的元素值和对应索引
            num_dict = {nums[i]: i for i in range(len(nums))}
            #创建第二个字典:存储target-列表中的元素的值
            num_dict2 = {i: target - nums[i] for i in range(len(nums))}
            #判断num_dict2的值是否是输入列表中的元素,如果是返回索引值,不是则往下进行
            result = []
            for i in range(len(nums)):
                j = num_dict.get(num_dict2.get(i))
                if (j is not None) and (j != i):
                    result = [i,j]
                    break
            return result
    
    #方法4:改进方法3,让代码简洁一些
    class Solution:
        def twoSum_way4(self, nums, target):
            """
            :param nums: 整数列表
            :param target:目标值
            :return:result 索引值
            """
            num_dict = {nums[i]: i for i in range(len(nums))}
            for i in range(len(nums) -1):
                difference = target - nums[i]
                if difference in num_dict and i != num_dict[difference]:
                    return [i,num_dict[difference]]
            return None
    

    终极写法:

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            dict = {}
            for index,num in enumerate(nums):
                another_num = target - num
                dict[num] = index
                if another_num in dict:
                    return [dict[another_num], index]
            return None
    

      

      

      

     

  • 相关阅读:
    The Tower of Hanoi
    POJ 3259:Wormholes
    第二数学归纳法
    Josephus Problem
    想成为Java高手的25个学习目标
    How to find a cycle of length 4?
    Fabonacci Numbers
    通过参数离线安装SharePoint 2010[转]
    Sharepoint2010文档库权限问题
    BizTalk 2010 学习笔记——第一章 BizTalk 2010 概述
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/10349797.html
Copyright © 2020-2023  润新知