码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode HOT 100

时间:2020-12-14 12:59:21      阅读:3      评论:0      收藏:0      [点我收藏+]

标签:lis   return   sum   ref   反转   lin   tar   tco   div   

记录

I

通过:1,
错误:206(递归返回条件和边界条件),

1.两数之和-简单

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lookup = {}
        for i in range(len(nums)):
            num = nums[i]
            if target - num in lookup:
                return [i, lookup[target - num]]
            else:
                lookup[num] = i

206.反转链表-简单

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        """
        迭代1:
        pre,1 cur,2,3,4,None
        pre,2,1 cur,3,4,None
        
        if head is None or head.next is None:
            return head 
        pre = ListNode(None)
        pre.next = head 
        cur = head 
        while cur.next:
            tmp = cur.next 
            cur.next = tmp.next 
            tmp.next = pre.next
            pre.next = tmp 
        return pre.next
        """
        """
        递归:
        # 1,2,3,4,None
        # reverse(2,3,4),1,None        
        if head is None or head.next is None: ## 易错点:head为空; 返回条件:递归到最后一个非空节点
            return head 
        node = self.reverseList(head.next)
        head.next.next = head 
        head.next = None 
        return node  
        """

LeetCode HOT 100

标签:lis   return   sum   ref   反转   lin   tar   tco   div   

原文地址:https://www.cnblogs.com/sandy-t/p/14100575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!