Leetcode学习(1)—— 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.

给出一个整数数组,返回两个加起来等于特定的目标的两个数的下标。

你可以假定每一个输入都会有一个精确的解答,并且你也许不会两次使用相同的元素。

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

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

这里写图片描述

# -*- coding:utf-8 -*-
class Solution(object):
    def twoSum(self, nums, target):
        # 以 k 为指针
        k = 0
        # 遍历 nums list
        for i in nums:
            # j 为另一个数
            j = target - i
            # 指针后移
            k += 1
            # rest_nums 为 nums 的剩余部分
            rest_nums = nums[k:]
            # 如果 j 在 rest_nums 中
            if j in rest_nums:
                # 则返回 i 和 j 的下标
                return [k-1, rest_nums.index(j) + k]


if __name__ == '__main__':
    print(Solution().twoSum((2, 7, 11, 15), 17))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值