LeetCode_Everyday:001 Two Sum

LeetCode_Everyday:001 Two Sum


LeetCode Everyday:坚持价值投资,做时间的朋友!!!

题目:

给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

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

代码

方法一: 暴力枚举法,时间复杂度:O(n2)O(n^2)

执行用时 :6812 ms, 在所有 Python3 提交中击败了5.96%的用户
内存消耗 :14.7 MB, 在所有 Python3 提交中击败了12.80%的用户

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """   
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return[i, j]
                
"""
For Example:    input:   nums = [2, 7, 11, 15]  target = 9
               output:   [0, 1]
"""             
nums = [2, 7, 11, 15]
target = 9

solution = Solution()
result = solution.twoSum(nums, target)
print('输出为:', result)    # [0, 1]

方法二: 两边找法,时间复杂度:O(n)O(n)

Tips: 需要注意的是使用这种方法的前提是列表有序(本题无序),无序可以先排序,但是排序之后需要找回原来的index,可以建立一个映射关系,所以如果只是针对此题,不建议使用,但是这种思路很好,对于有序列表且多维度搜索有奇效。


class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        i = 0
        j = len(nums) - 1
        while i < j:
            sum = nums[i] + nums[j]
            if sum == target:
                return [i ,j]
            elif sum < target:
                i += 1
            else:
                j -= 1

"""
For Example:    input:   nums = [2, 7, 11, 15]  target = 9
               output:   [0, 1]
"""             
nums = [2, 7, 11, 15]
target = 9

solution = Solution()
result = solution.twoSum(nums, target)
print('输出为:', result)      # [0, 1]

方法三: 哈希法,时间复杂度:O(n)O(n)

执行用时 :84 ms, 在所有 Python3 提交中击败了48.61%的用户
内存消耗 :15.1 MB, 在所有 Python3 提交中击败了5.48%的用户
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for index, num in enumerate(nums):
            if target - num in dic:
                return [dic[target-num], index]
            else:
                dic[num] = index

"""
For Example:    input:   nums = [2, 7, 11, 15]  target = 9
               output:   [0, 1]
"""             
nums = [2, 7, 11, 15]
target = 9

solution = Solution()
result = solution.twoSum(nums, target)
print('输出为:', result)    # [0, 1]

图解:

引用的图片展示的是方法四的动态过程,可以帮助分析,很不错

参考

  1. https://github.com/MisterBooo/LeetCodeAnimation

此外

  • 原创内容转载请注明出处
  • 请到我的GitHub点点 star
  • 关注我的 CSDN博客
  • 关注公众号:CV伴读社

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章