Two Sum

Two Sum

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.

example
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

这道题是进入leetcode的第一道题目,大致的思路最开始就是暴力解法,将数组中的每两个数相加,然后和target相比,计算了下复杂度,大概在O(n2)。换个思路,用target减去当前的数,在从数组中查询是否存在这个数。但是没有想到hash的办法,导致其实复杂度还是在O(n2)。但也通过了测试,看了网上有很多种办法,可以逐一学习一下。

主要的方法有两种:
1. 先排序然后用双指针向中间夹逼,复杂度O(nlogn)
2. 用Map记录出现过的数,查找有没有跟当前的数构成target,复杂度为O(nlogn)。相对于自己直接的比较,还是用了hash比较快

方法一,跑下来的速度在40ms

class Solution(object):
    def twoSum(self, nums, target):
        nums_sorted = sorted(nums)

        left = 0
        right = len(nums) - 1

        while True:
            if nums_sorted[left] + nums_sorted[right] == target:
                post1 = nums.index(nums_sorted[left])
                post2 = nums.index(nums_sorted[right])
                if post2 == post1:
                    post2 = nums[post1+1:].index(nums_sorted[right]) + post1 + 1
                return min(post1+1, post2+1), max(post1+1, post2+1) 
            elif nums_sorted[left] + nums_sorted[right] < target:
                left += 1
            elif nums_sorted[left] + nums_sorted[right] > target:
                right -= 1

方法二,跑下来的速度在48ms反而慢了些

class Solution(object):
    def twoSum(self, nums, target):
        map = {}
        for i, value in enumerate(nums):
            if target-value in map:
                return map[target-value]+1, i+1
            else:
                map[value] = i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值