leetcode 1 Two Sum
题目地址:https://leetcode.com/problems/two-sum/description/
Tag: Array
Difficulty: 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.
Example:
1 | Given nums = [2, 7, 11, 15], target = 9, |
解题思路
用一层for循环遍历nums数组中的元素x,令k = target-x
,用in
判断k是否在nums数组中,如果在,返回x和k
代码实现
1 | class Solution: |
第10行,i != nums.index(k)
是为了防止nums=[3,3], target=6这样的情况,需要过滤掉k和nums[i]处在同一个位置。
第二种思路还有另一种实现方法,通过字典构建一个哈希表:
1 | class Solution: |
在Discuss区还看到一种清奇的实现方法,代码地址
1 | class Solution(object): |