分享

【记录帖】(No.001)从零打卡刷Leetcode

 太极混元天尊 2018-05-25

资源干货第一时间送达!

小詹学Python
无套路资源共享 
无广告技术交流群



写在前边:

小詹一直觉得自己编程能力不强,想在网上刷题,又怕不能坚持。不知道有木有和小伙伴和小詹一样想找个人一起刷题呢?欢迎和小詹一起定期刷leetcode,每周一周五更新一题,每一题都吃透,欢迎一题多解,寻找最优解欢迎小伙伴们把自己的思路在留言区分享出来噢~



No.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.

题目大意:给出一个数字列表和一个目标值(target),假设列表中有且仅有两个数相加等于目标值,我们要做的就是找到这两个数,并返回他们的索引值。

例如:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


小詹第一反应就是两层循环就可以解决,小case,的确思路简单,但是时间复杂度,你懂得!很简单就能想到的代码如下:

def twoSum(self, nums, target):
   '''
   :type nums: List[int]
   :type target: int
   :rtype: List[int]
   '''

   result = []
   for i in range(len(nums)):
      for j in range(i+1, len(nums)):
          if nums[i] + nums[j] == target:
              result.append(i)
              result.append(j)
              return result

其实这里也可以用一层循环即可实现,因为我们知道有且仅有一个解;我们可以通过判断target与某一个元素的差值是否也在列表之中即可,这个和两层循环思路类似,但是不难想到计算次数就下降了,代码如下:

def twoSum(self, nums, target):
   '''
   :type nums: List[int]
   :type target: int
   :rtype: List[int]
   '''

   result = []
   for i in range(len(nums)):
      oneNum = nums[i]
      twoNum  = target - oneNum
      if twoNum in nums:
         j = nums.index(twoNum)
         if i != j:
            result.append(i)
            result.append(j)
            return result

的确两种方案都轻松通过了,but用时过长,排名老靠后了。之后小詹在网上找到了另一种方案,整体思路和一层循环的方案二有点类似:通过创建字典,将nums里的值和序号对应起来,并创建另一个字典存储目标值(Target)-nums的值,通过判断该值是否在nums内进行判断并返回其对应索引值,代码如下:

def twoSum(self, nums, target):
       '''
       :type nums: List[int]
       :type target: int
       :rtype: List[int]
       '''

       # 创建字典一,存储输入列表的元素值和对应索引
       num_dict = {nums[i]:i for i in range(len(nums))}
       print(num_dict)
       # 创建另一个字典,存储target-列表中的元素的值,小詹称为num_r吧,好表达
       num_dict2 = {i:target-nums[i] for i in range(len(nums))}
       print(num_dict2)
       # 判断num_r是否是输入列表中的元素,如果是返回索引值,不是则往下进行
       result = []
       for i in range(len(nums)):
           j = num_dict.get(num_dict2.get(i))
           if (j is not None) and (j!=i):
               result = [i,j]
               break
       return result

该方案,在时间效率上还较为理想,小詹亲测结果排名如下:

不知道小伙伴们能否提出更加节约时间的方案呢?如果有请联系小詹,在下一次打卡时候分享给大家!独乐乐不如众乐乐噢!


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多