题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9. Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
分析
题目中的输入为:列表
nums
n
u
m
s
, 目标值
target
t
a
r
g
e
t
.
输出为:符合条件的列表元素下标。
题目中给出的假设条件为:每组输入对应唯一的解,同时返回的列表元素不可重复。
解答
下面解答的编程语言均为Python3。由于题目要求找出符合条件的两个元素的下标,默认返回下标时,按照从小到大顺序;而当无符合条件的元素组合时,定义返回[ ]。
解法一:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_len = len(nums)
for i in range(num_len):
num_i = nums[i]
for j in range(i+1, num_len):
if num_i + nums[j] == target:
return [i, j]
return []
使用双层循环对每一种可能的元素对进行判断,一旦发现符合条件的元素对,则返回结果。该方法的思路简单,实现起来也比较容易,但复杂度为 O(n2) O ( n 2 ) ,对于元素较多的列表不太适用。
解法二:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_dict = dict()
for i, k in enumerate(nums):
if target - nums[i] in num_dict:
return [num_dict[target-nums[i]], i]
num_dict[k] = i
return []
dict,即字典,是python语言中重要的一种数据结构。dict采用key-value键对的方式储存数据,而key的寻址则采用hashmap的方式,便于能够快速查找和修改字典元素。当没有寻址冲突发生时,其查找效率为 O(1) O ( 1 ) , 此时上述解法的复杂度为 O(n) O ( n ) 。