Leetcode 两数之和

Leetcode 两数之和

两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

解题思路

从列表头部开始每次取出一个数字: A, 并记录取数的索引: k,
在剩余的数组: ary[k+1:] 中查找: target - A 的索引 j,
如果找到返回: [k,j], 没有找到就从头部继续往后取出数字.

Answer

 1#
 2# @lc app=leetcode.cn id=1 lang=python3
 3#
 4# [1] 两数之和
 5#
 6
 7# @lc code=start
 8class Solution:
 9    def twoSum(self, nums: List[int], target: int) -> List[int]:
10        cnt = 0
11        while len(nums):
12            a = nums.pop(0)
13            want = target - a
14            if want in nums:
15                idx = nums.index(want)
16                return [cnt, idx+cnt+1]
17            cnt = cnt + 1
18
19# @lc code=end
 1#
 2# @lc app=leetcode.cn id=1 lang=python3
 3#
 4# [1] 两数之和
 5#
 6
 7# @lc code=start
 8class Solution:
 9    def twoSum(self, nums: List[int], target: int) -> List[int]:
10        cnt = 0
11        lens = len(nums)
12        while cnt < lens - 1:
13            a = nums[cnt]
14            if target - a in nums[cnt + 1:]:
15                return [cnt,nums.index(target - a, cnt + 1)]
16            cnt = cnt + 1
17
18# @lc code=end

Accepted

 29/29 cases passed (768 ms)
 Your runtime beats 43.42 % of python3 submissions
 Your memory usage beats 13.41 % of python3 submissions (14.6 MB)