从leetcode 1. Two Sum看迭代器和循环的执行效率
最近从头开始刷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.Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
很自然想到用双重循环,
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in xrange(len(nums) - 1):
for j in xrange(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
但是很自然地,程序运行时间超出限制,因此我就想先进行一个排序,并对原数组做一个拷贝,然后按照首尾遍历最多遍历n个元素将复杂度缩减到排序的O(n lg(n))加上遍历的O(n),这里要注意可能存在重复元素的情况,稍微处理一下就可以了,代码如下:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num = nums.copy()
nums.sort()
j = len(nums) - 1
for i in range(len(nums)):
while(j > i and nums[j] > target - nums[i]):
j -= 1
if nums[j] == target - nums[i]:
break
r = num.index(nums[i])
if nums[i] == nums[j]:
num[r] = 'a'
s = num.index(nums[j])
return [r,s]
意外地我在网上看到了一个利用迭代器做的方法,先把代码贴上来:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i, num in enumerate(nums):
sub_num = target - num
if sub_num in nums:
t_index = nums.index(sub_num)
if t_index != i:
return [i, t_index]
这里其实和最开始两重循环的实质是一样的,但是特殊的地方在于这里用了迭代器,提交代码上去也是可以通过的,网上也有很多关于迭代器和普通循环的效率比较,这里就不再赘述了。