[LeetCode]題解(python):001-Two-Sum


題目來源:

https://leetcode.com/problems/two-sum/


題意分析:

      這道題目是輸入一個數組和target,要在一個數組中找到兩個數字,其和為target,從小到大輸出數組中兩個數字的位置。題目中假設有且僅有一個答案。


題目思路:

     如果直接暴力解決,時間復雜度為(O(n^2)),很明顯這種方法會TLE。

     那么如果給定的數組是有序的會不會降低難度呢?如果是有序的數組,那么我們可以用“夾逼定理”來處理。簡單來說就是首尾相加,如果比target大,則將尾數左移,如果小了首尾右移,直到兩個數相加剛好等於target,那么我們可以先將數組排序,然后用“夾逼定理”,這種方法的時間復雜度為(O(nlogn)。這種方法要注意的是排序的時候要記錄數組原來的位置,然后再排序。

    接下來我來介紹最后一種方法。在python里面有一個dictionary的和C++ 的map功能一樣。首先,我們建立一個字典,d = {},字典的key是數組的值num,value是相應的位置, 然后只要滿足 num 和 target - num都在字典里面則找到答案。這種方法的時間復雜度是(O(n))。


代碼(python):

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}# d is a dictionary to map the value of nums and the index in nums
        size = 0
        while size < len(nums):
            if not nums[size] in d:
                d[nums[size]] = size + 1 #if nums[size] doesn't exist in d ,create it
            if target - nums[size] in d: #if nums[size] and target - nums[size] are both in d
                if d[target-nums[size]] < size + 1: # one situation should be minded nums[size] == target - nums[size]
                    ans = [d[target - nums[size]] , size + 1]# for example [0,1,2] 0 and [0,1,2,0],0
                    return ans
            size = size + 1
View Code

 


 

PS:注意情況,注意特殊情況。比如target剛好是數組中某個數的2倍,且這個數只有一個或者二個的時候,如[3],6和[3,2,3],6。


轉載請說明出處:http://www.cnblogs.com/chruny/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM