题解 | #两数之和#

两数之和

http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f

#
# 
# @param numbers int整型一维数组 
# @param target int整型 
# @return int整型一维数组
#
class Solution:
    def twoSum(self , numbers , target ):
        # write code here
        # 优化遍历法
        for i in range(len(numbers)-1,0,-1) :               #倒序操作,保证大的index值始终在后面
            sub = target - numbers[i]
            if sub in numbers and numbers.index(sub) != i :
                return [numbers.index(sub)+1,i+1]

抄的代码,和哈希法的思路很像了,因为只要目标值减去当前值,找数组中和差值一致的值即可,无需嵌套循环就能省时间

全部评论

相关推荐

2025-12-13 12:38
惠州学院 直播运营
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务