Leet Code OJ 1. Two Sum [Difficulty: Easy]

1.两数之和

出现频度为5

给定一个整数数组和一个目标值,找出数组中和为目标值的两个

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

Python代实现:

方法一:暴力法

最简单的思路,就是用两个for循环分别遍历数组中的数,找到两个数的和为target。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = len(nums)
        for i in range(0,l):
            for j in range(0,l):
                if j != i:
                    if nums[i]+nums[j] == target:
                        return [i,j]

时间复杂度为O\left ( n^{2} \right ),两个for循环嵌套,执行一次外部的for循环需要执行n次内部for循环,耗费O\left ( n \right )时间,故一共为n*n

空间复杂度O\left ( 1 \right )

方法二:

先把值和序号存在字典中,这个字典中,key为数值,value为对应的序号0,1,2...,然后遍历字典,找target-nums[i]是否在字典中,注意两个数据的序号值不相等。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        l = len(nums)
        for i in range(l):
            dic[nums[i]] = i
        for i in range(l):
            if target-nums[i] in dic and i < dic[target-nums[i]]:
                return [i,dic[target-nums[i]]]

时间复杂度O\left ( n \right ),我们把包含有 n个元素的列表遍历两次,所以时间复杂度为O\left ( n \right )

空间复杂度O\left ( n \right ) ,所需的额外空间取决于字典中存储的元素数量,最多存储了 n 个元素。 

方法三:

在迭代中,将数组中的某值的对应计算值放入字典的同时,一边检测这个值是否已经存在字典中,若不存在则把他相应的计算值存入字典,若存在则将他们返回。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        l = len(nums)
        for i in range(l):
            a = target-nums[i]
            if nums[i] in dic:
                return [dic[nums[i]],i]
            else:
                dic[a] = i

时间复杂度O\left ( n \right ),只遍历了包含n个元素的列表一次。在表中进行的每次查找只花费 O\left ( 1 \right )的时间。

空间复杂度O\left ( n \right ), 所需的额外空间取决于字典中存储的元素数量,最多需要存储 n 个元素。

猜你喜欢

转载自blog.csdn.net/Mr_xuexi/article/details/83274246