【Python】【algorithm】Leetcode日记#1 Two sum
前记
啊~虽然豆花上了一年大学感觉自己码的能力还是很一般般,所以就来刷著名的leetcode,也为了熟悉python,基本选用的语言就是python。
Leetcode传送门
第一题!
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.
一组数列,找出其中两个数,要求两数和等于目标值,并导出两个数的位置。
分析一下
先考虑比较好想的方法,找满足的两个数,可以一个一个试,找到和满足的两个数,这样需要历变两次,时间是O(n2)。不过我们可以换一种方式想想,我们可以找一个数,然后找这个数和目标值的差,在看数列中有没有满足的差,当然,要是用两个循环的话还是需要O(n2)的时间。不过,我们可以尝试只用一次循环搞定,Python中提供了dictionary(其他语言应该也有代替的方法),dictionary中元素都有Key-Value两个值,我们不妨一个存其中一个数,另一个存差值实现一次循环解决。
code
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) <= 1:
return False
dic_buff = {}
for i in range(len(nums)):
if nums[i] in dic_buff:
return [dic_buff[nums[i]],i]
else:
dic_buff[target - nums[i]] = i
前面O(n^2)的方法官网上也有传送门
后记
虽然这是道easy题目,但是豆花还是做了很长时间,并且也参考了网上大神的高见,在这里谢谢自己的感悟与分享,希望大家也能赏脸本豆花,有什么想说的可以尽情留言噻!

浙公网安备 33010602011771号