Leetcode: TwoSum

本文详细解析了LeetCode经典题目“两数之和”的解决方案,对比了三种不同的算法实现,包括原始的暴力搜索、基于排序的双指针策略和高效的哈希表查找方法。通过对每种方法的时间复杂度和空间复杂度的分析,强调了算法优化的重要性。

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

题目:

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 haveexactly one solution, and you may not use thesame element twice.

example:  Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

第一次刷,花了两个小时才写出了一个又臭又长的破代码,虽然也通过了测试,但是写的真的是太次了,有太多的进步空间,

自己的代码:

import numpy as np 
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i,num in enumerate(nums):
            if target - num in nums:
                if (target - num) != num:
                    temp = num
                    break
                else:
                    nums[i] = 0.1
                    if num in nums:
                        temp = num
                        break
                
        nums = np.array(nums)
        num1 = temp
        num2 = target - num1
        if num1 == num2:
            mask1 = 0.1 == nums
            mask2 = num2 == nums
        else:
            mask1 = num1 == nums
            mask2 = num2 == nums
        index1 = 0
        index2 = 0
        for i in mask2:
            if i == True:
                break
            index2 += 1
        for i in mask1:
            if i == True:
                break
            index1 += 1 
        return [index1, index2]

通过这段代码发现自己的思维禁锢在了要寻找特定的索引时只会用遍历的操作,对数据结构理解的不到位,写了大量的冗余代码操作。开始的时候也没有考虑到输入的多种情况,以至于提交的时候破绽百出,最终也就只能使用大量的判断语句来处理各类的情况。

参考了其他人的两段代码,这两段代码都很简洁,而且效果都比我的好。

第一个使用的是排序算法来实现的,时间复杂度为O(nlogn)。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        sorted_id = sorted(range(len(nums)), key=lambda k: nums[k])
        head = 0
        tail = len(nums) - 1
        sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
        while sum_result != target:
            if sum_result > target:
                tail -= 1
            elif sum_result < target:
                head += 1
            sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
        return [sorted_id[head], sorted_id[tail]]

其中学到了python的内置函数sorted的高级用法,可以用来找出一个列表的排序索引,再根据首尾的索引指示来计算与target值是否相同,经过这个搜索过程之后就得到了最终的结果索引。

第二个使用的是哈希表来实现的,利用空间复杂度来换取时间复杂度,时间复杂度编程了O(n)。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

利用字典,即哈希表来纪录之前操作过的数据,再到后来的搜索中,只要寻找本身互补的数是否在哈希表中即可,在的话就结束了算法,找到了结果索引。

 

算法这种东西真的是很神奇,各种实现各种性能,平常得多看看别人的代码和自己多写写代码才能够巩固自己。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值