今天开始正式进行LeetCode的刷题之旅,自己的编程算法能力都太差了,所以决定进行苦练,查到的代码和解法,优化以及个人的理解,就这样。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
首先想到的解决思路是通过两次循环,每次循环遍历列表,这种算法的时间复杂度是O(n^2)。
class Solution:
def twoSum(self, nums, target):
len_nums = len(nums)
for i in range(len_nums):
for j in range(i + 1, len_nums):
if nums[i] + nums[j] == target:
return [i, j]
return []
直接忽略这种解法。
class Solution:
def twoSum(self, nums, target):
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]]
解析:
len(nums)=4,range(len(nums))={0,1,2,3}的随机排序;
key=lambda k: nums[k]输出键k对应的值;
sorted对根据key值对range进行排序,sorted_id = [0,1,2,3]
head = 0,tail = len(nums)-1=4-1=3;
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]=nums[0]+nums[3]=2+15=17;
while sum_result != target,if 17>9,tail-1=2;
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]=nums[0]+nums[2]=2+11=13;
while sum_result != target,if 13>9,tail-1=1;
sum_result = nums[sorted_id[head]] + nums[sorted_id[tail]]=nums[0]+nums[1]=2+7=9;
跳出while,return [sorted_id[head], sorted_id[tail]]=[0,1].
两个代码都用到python的函数,第一个是enumerate
,第二个是sorted
,即便是简单题,我也不太会。。。只能多积累,培养自己的编程思维。。。
class Solution:
def twoSum(self, nums, target):
nums_hash = {}
nums_len = len(nums)
for i in range(nums_len):
dif = target - nums[i]
if dif in nums_hash:
return [nums_hash[dif], i]
nums_hash[nums[i]] = i
return []
完整的代码,可以直接运行。
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
keys = {}
for i, v in enumerate(nums):
if target-v in keys:
return [keys[target-v],i]
else:
keys[v] = i
return None
nums = [2,7,11,15],target = 9,进行if len(nums) <= 1,符合,跳过;
创建一个keys = {},空字典;
for i, v in enumerate(nums),对nums进行遍历,i,v对应的键,值;
if 9-2 = 7 in keys,False,else:keys[2] = 0;
if 9-7 = 2 in keys,True,return [keys[target-v],i] = [keys[9-7=2],1] = [0,1].