数组1 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

解法1:利用数组结构

(1)暴力求解,两层循环,奇怪的是空间复杂度也很高???

复杂度分析:

时间复杂度:O(n^2)

对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。因此时间复杂度为 O(n^2)。

空间复杂度:O(1)。

(2)比暴力好一点,看着一层循环,但需要每次遍历数组的其他部分来寻找它对应的目标元素,应该时间复杂度也是 O(n^2),奇怪的是比暴力法运行快很多貌似???

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        for i in range(len(nums)):

            result=[]

            result.append(i)

            if (target-nums[i]) in nums[i+1:]:

                result.append((nums[i+1:].index(target-nums[i]))+i+1)

                break

            else:

                continue

        return result


解法2:利用哈希结构,通过以空间换取速度的方式,我们可以将查找时间从 O(n)O(n) 降低到 O(1)

(1)两遍哈希,复杂度分析:

时间复杂度:O(n),

我们把包含有 nn 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1) ,所以时间复杂度为 O(n)。

空间复杂度:O(n),所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n 个元素。

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        hash1={}

        for i in range(len(nums)):

            hash1[nums[i]]=i

        for i in range(len(nums)):

            result=[]

            result.append(i)

            if ((target-nums[i]) in hash1) and hash1[target-nums[i]]!=i:

                result.append(hash1[target-nums[i]])

                break

            else:

                continue

        return result

(2)一遍哈希,相当于上边方法的倒序,减小时间和空间复杂度,但最坏情况还都是o(n)

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        hash1={}

        result=[]

        for i in range(len(nums)):

            if ((target-nums[i]) in hash1) and hash1[target-nums[i]]!=i:

                result.append(hash1[target-nums[i]])

                result.append(i)

                break

            else:

                hash1[nums[i]]=i

        return result

你可能感兴趣的:(数组1 两数之和)