[LeetCode] Two Sum

来源:互联网 发布:手机自选股软件 编辑:程序博客网 时间:2024/06/06 20:03

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 copyclass 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

从最后时间来看,第一种方法比第二种方法快近一半

0 0
原创粉丝点击