2018年9月9日 周日
#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].
问题分析:
本题难度为Easy!已给出的函数定义为:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
其中nums为列表,target为一个整型变量,需要返回的结果为一个列表。
本题的目标是寻找一组存储整数的列表中和为一个目标整数的两个整数的下标,最无脑的办法就是通过双层嵌套循环来遍历寻找和为目标值的下标,但这样时间复杂度为O(n^2),当列表数据太大时会出现超时,无法通过检测。
又想到python中列表有index()方法,用于从列表中找出某个值第一个匹配项的索引位置。所以可以把双层嵌套循环改进为一层循环,将目标值和循环值的差作为index()方法的参数获取另一个值的下标。这样时间复杂度变为O(n)。代码如下:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i=0
for num in nums:
if (target-num) in nums and nums.index(target-num)!=i:
return [i,nums.index(target-num)]
i+=1
python中有enumerate()函数,用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标(一般用在 for 循环当中)。因此,代码可以进一步改进为:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i,num in enumerate(nums):
if (target-num) in nums and nums.index(target-num)!=i:
return [i,nums.index(target-num)]