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伴讀社

在這裏插入圖片描述

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