[LeetCode] Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

簡單來說,這道題求的是在數組中兩元素的和等於給定值。

最先想到的方法就是兩層for循環,暴力破解,但這明顯會超時。涉及到數組的情況大多數首先需要排序,但這道題排序有什麼用?這裏有這樣一種思路:

數組排序後設置head、end兩指針,分別指向數組的頭和尾,然後判斷,如果arr[head] + arr[end] > sum,則end -= 1,如果arr[head] + arr[end] < sum,則head += 1,這樣就可以在O(N)的時間內找出這兩個元素,然後在查找這兩個元素在原數組的位置。

另外一種思路:hash表是典型的用空間換時間的方法,所以當超時時也需要考慮能不能用hash,這道題的時間主要耗在了對元素的查找上,所以可以這樣做,遍歷數組arr,查看sum - arr[i] 是不是在hash表中,這樣也可以在O(N)中找出。

第一種:

class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[]}
    def twoSum(self, nums, target):
        nums_dict = {}
        nums_set = set(nums)
        for index1 in range(len(nums)):
            dlt = target - nums[index1]
            if dlt in nums_set:
                for index2 in range(len(nums)):
                    if nums[index2] == dlt and index1 != index2:
                        ret = [index1 + 1, index2 + 1]
                        ret.sort()
                        return ret
        return 0

第二種:

import copy
class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[]}
    def twoSum(self, nums, target):
        tmpNums = copy.copy(nums)
        tmpNums.sort()
        head = 0
        end = len(tmpNums) - 1
        while head < end:
            if tmpNums[head] + tmpNums[end] > target:
                end -= 1
            elif tmpNums[head] + tmpNums[end] < target:
                head += 1
            else:
                index1 = None
                index2 = None
                for i in range(len(nums)):
                    if nums[i] == tmpNums[head] and None == index1:
                        index1 = i
                    elif nums[i] == tmpNums[end] and None == index2:
                        index2 = i
                if None != index1 and None != index2:             
                        retList = [index1 + 1, index2 + 1]
                        retList.sort()
                        return retList

從最後時間來看,第一種方法比第二種方法快近一半
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章