[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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值