[LeetCode]题解(python):001-Two-Sum

本文解析LeetCode经典题目“两数之和”的多种解法,包括暴力搜索、夹逼定理及使用哈希表的方法,并分析每种方法的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:

https://leetcode.com/problems/two-sum/


题意分析:

      这道题目是输入一个数组和target,要在一个数组中找到两个数字,其和为target,从小到大输出数组中两个数字的位置。题目中假设有且仅有一个答案。


题目思路:

     如果直接暴力解决,时间复杂度为(O(n^2)),很明显这种方法会TLE。

     那么如果给定的数组是有序的会不会降低难度呢?如果是有序的数组,那么我们可以用“夹逼定理”来处理。简单来说就是首尾相加,如果比target大,则将尾数左移,如果小了首尾右移,直到两个数相加刚好等于target,那么我们可以先将数组排序,然后用“夹逼定理”,这种方法的时间复杂度为(O(nlogn)。这种方法要注意的是排序的时候要记录数组原来的位置,然后再排序。

    接下来我来介绍最后一种方法。在python里面有一个dictionary的和C++ 的map功能一样。首先,我们建立一个字典,d = {},字典的key是数组的值num,value是相应的位置, 然后只要满足 num 和 target - num都在字典里面则找到答案。这种方法的时间复杂度是(O(n))。


代码(python):

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}# d is a dictionary to map the value of nums and the index in nums
        size = 0
        while size < len(nums):
            if not nums[size] in d:
                d[nums[size]] = size + 1 #if nums[size] doesn't exist in d ,create it
            if target - nums[size] in d: #if nums[size] and target - nums[size] are both in d
                if d[target-nums[size]] < size + 1: # one situation should be minded nums[size] == target - nums[size]
                    ans = [d[target - nums[size]] , size + 1]# for example [0,1,2] 0 and [0,1,2,0],0
                    return ans
            size = size + 1
View Code

 


 

PS:注意情况,注意特殊情况。比如target刚好是数组中某个数的2倍,且这个数只有一个或者二个的时候,如[3],6和[3,2,3],6。


转载请说明出处:http://www.cnblogs.com/chruny/

转载于:https://www.cnblogs.com/chruny/p/4788804.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值