Leetcode习题:1. Two Sum

本文介绍了一种解决“两数之和”问题的有效算法。该算法通过排序数组并使用双指针技巧来查找目标值的两个元素,避免了双重循环的高复杂度。文章详细解释了算法的实现步骤,并提供了Python代码示例。

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

难度:Easy

链接:点击打开链接

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.



思路:

让你从一个数组中找出两个数,他们相加等于target,自然是可以用两个循环来做,但是这样复杂度会很高。

所以可以换一种方法:

先将数组排序,并用两个指针指向头尾,检验两个指针指向的值,相加如何,如果相等,返回结果(如果用的是index,需要再处理下,因为需要返回index,而排序已经打乱了原先的index,最开始的index事先复制一份,在复制的数组中找头尾指针指向的值,为防止结果是重复的两个数字,尾指针指向的值在复制的数组中要反向遍历)

如果是小于结果,头指针+1

如果是大于结果,尾指针-1

这样会不断逼近想找到的两个数字

代码:

class Solution:
    def twoSum(self, nums, target):
        store = copy.deepcopy(nums)
        nums.sort()
        front = 0
        back = len(nums)-1
        while (front < back):
            if (nums[front] + nums[back] == target):
                r = list(range(len(store)))
                r.reverse()
                back_index = 0
                for x in r:
                    if (store[x] == nums[back]):
                        back_index = x
                        break
                return [store.index(nums[front]),back_index]
            elif nums[front] + nums[back] < target:
                front = front+1
            elif nums[front] + nums[back] > target:
                back = back-1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值