题目:
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 haveexactly one solution, and you may not use thesame element twice.
example: Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
第一次刷,花了两个小时才写出了一个又臭又长的破代码,虽然也通过了测试,但是写的真的是太次了,有太多的进步空间,
自己的代码:
import numpy as np
class Solution(object):
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:
if (target - num) != num:
temp = num
break
else:
nums[i] = 0.1
if num in nums:
temp = num
break
nums = np.array(nums)
num1 = temp
num2 = target - num1
if num1 == num2:
mask1 = 0.1 == nums
mask2 = num2 == nums
else:
mask1 = num1 == nums
mask2 = num2 == nums
index1 = 0
index2 = 0
for i in mask2:
if i == True:
break
index2 += 1
for i in mask1:
if i == True:
break
index1 += 1
return [index1, index2]
通过这段代码发现自己的思维禁锢在了要寻找特定的索引时只会用遍历的操作,对数据结构理解的不到位,写了大量的冗余代码操作。开始的时候也没有考虑到输入的多种情况,以至于提交的时候破绽百出,最终也就只能使用大量的判断语句来处理各类的情况。
参考了其他人的两段代码,这两段代码都很简洁,而且效果都比我的好。
第一个使用的是排序算法来实现的,时间复杂度为O(nlogn)。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sorted_id = sorted(range(len(nums)), key=lambda k: nums[k])
head = 0
tail = len(nums) - 1
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
while sum_result != target:
if sum_result > target:
tail -= 1
elif sum_result < target:
head += 1
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]
return [sorted_id[head], sorted_id[tail]]
其中学到了python的内置函数sorted的高级用法,可以用来找出一个列表的排序索引,再根据首尾的索引指示来计算与target值是否相同,经过这个搜索过程之后就得到了最终的结果索引。
第二个使用的是哈希表来实现的,利用空间复杂度来换取时间复杂度,时间复杂度编程了O(n)。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None
利用字典,即哈希表来纪录之前操作过的数据,再到后来的搜索中,只要寻找本身互补的数是否在哈希表中即可,在的话就结束了算法,找到了结果索引。
算法这种东西真的是很神奇,各种实现各种性能,平常得多看看别人的代码和自己多写写代码才能够巩固自己。