leetcode algorithm1 twoSum

leetcode algorithm1 twoSum

问题

Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.

问题非常的简单,但是如果使用暴力方法搞二重循环,很有可能超时(C不会,但是python Java可能会,虽然给的时间限制不一样)

思路

注意题目中给的提示:每个元素只会出现一次。而且他只让你返回一组二元组。这种情况下,可以使用HashMap的数据结构来实现O(n)的复杂度。用空间换取时间。

既,用一个和数组等长的hashmap存储数组中各个元素的补位所在的位置。由于Hash函数的使用,在map中查找的时间复杂度为O(1),如果map是允许键值重复的实现,这样时间复杂度可能会降至O(n)。这里我们就使用HashMap。

python实现

twoSum函数是蛮力的方法,twoSumBetter是用map且只跑一趟的方法

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for index1 in range(len(nums)):
            for index2 in range(index1+1,len(nums)):
                if nums[index1] + nums[index2] == target:
                    list = []
                    list.append(index1)
                    list.append(index2)
                    print(list)
                    return list


    def twoSumBetter(self, nums, target):
        if len(nums) <= 1:
            return False
        buffer_dict = {}
        for i in range(len(nums)):
            if nums[i] in buffer_dict:
                return [buffer_dict[nums[i]],i]
            else:
                buffer_dict[target-nums[i]] = i

instance = Solution()
# instance.twoSum([3,4,5,1],6)
print(instance.twoSumBetter([3,4,5,1],6))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值