LeetCode刷题笔记(二)

1.Remove Nth Node From End of List

Medium

Description

Given a linked list, remove the n-th node from the end of list and return its head.

Example

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.

Follow up:
Could you do this in one pass?

Code

解题思路:首先,题目要求删除链表中从后往前的第N个数,因该链表为单向链表,所以只能从前向后遍历。既然要从后删除第N个数,即从前删除第len(linklist)-N个数,因此,第一步需要计算出链表的长度,第二步遍历删除第len(linklist)-N个数即可,详细可看代码。

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

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        if head is None: return head  # 若第一个点即为None则直接返回
        head_new = head  # 浅复制链表
        length = 0  # 初始化链表长度
        while head_new:  # 循环遍历链表,计算链表长度
            head_new = head_new.next
            length += 1
        diff = length - n  # 计算差值,这里的差值为非负数,因为n为有效值
        if diff == 0: return head.next  # 若差值为0,说明要删除第一个值,则直接返回head后面的节点即可
        head_new = head  # 再次浅复制
        for _ in range(diff - 1):  # 遍历找到需要删除节点的前一个节点,所以需要-1
            head_new = head_new.next
        head_new.next = head_new.next.next  # 找到后将前一节点直接指向后一节点即可
        return head  # 因是浅复制,所以原变量值依然会变,直接返回

时间复杂度为O(n),空间复杂度为O(n)。

2.Valid Parentheses(括号)

Easy

Description

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:
   1.Open brackets must be closed by the same type of brackets.
   2.Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example

Example 1

Input: “()”
Output: true

Example 2

Input: “()[]{}”
Output: true

Example 3

Input: “(]”
Output: false

Example 4

Input: “([)]”
Output: false

Example 5

Input: “{[]}”
Output: true

Code

解题思路:略,详细看代码。

class Solution:
    def isValid(self, s: str) -> bool:
        if not s: return True  # 若字符串为空则返回True
        dict_Parentheses = {'(':')', '{':'}', '[':']'}  # 定义匹配字典
        should_have, i = [], 0  # should_have为字符串中应该要有的字符,i可判断仅有右括号时的情况
        for p in s:  # 遍历字符串
            a = dict_Parentheses.get(p,'')  # 获取字典中匹配上的右括号
            if a:  # 若能取到值,should_have列表为增加匹配上的右括号
            	should_have.append(a)
            else:  # 若没取到,说明是右括号,需+1
                i += 1
            if should_have and p == should_have[-1]:   # 如果列表里有值且当前p为最新加入的右括号,则将该右括号从列表中删除
                should_have.pop()
                i -= 1  # 同时i-1,若最后i不为0,说明之前多匹配了右括号而没有左括号
        return should_have == [] and i == 0  # 若列表为空,且i==0,说明为True

时间复杂度为O(n),空间复杂度为O(n)。

3.Merge Two Sorted Lists

Easy

Description

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Note:
Given n will always be valid.

Follow up:
Could you do this in one pass?

Code

解题思路:略,详细看代码。

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        l3 = l4 = ListNode(0)  # 创建两个初始节点
        while l1 and l2:  # 循环遍历两个链表,若有一个遍历到为空则说明另一个的剩余都偏大,直接加在最后即可
            if l1.val < l2.val:  # 当前值小者,被赋值给l3
                l3.next = l1
                l1 = l1.next
            else:
                l3.next = l2
                l2 = l2.next
            l3 = l3.next
        l3.next = l1 or l2
        return l4.next  # 返回初始节点的下一节点即可

时间复杂度为O(m+n),空间复杂度为O(m + n)。

4.Validate Binary Search Tree

Medium

Description

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

Example

Example 1

   2
  / \ 
 1   3
Input: [2,1,3]
Output: true

Example 2

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Code

解题思路:首先题目要求是判断一个二叉树是否合法(有效)。通过递归比较左子树的值是否小于等于右子树。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def __init__(self):
        self.LastNode = float('-inf')  # 初始化,定义一个最小值,与二叉树中最小的值比较(最小的值是最左叶子结点)
    def isValidBST(self,root):
        if root is None:return True  # 初始的树为空则返回True,同时在遍历到叶子结点的下一个结点为空也返回True
        if not(self.isValidBST(root.left)):return False  # 如果左子树合法,则往下,否则返回False
        if root.val<=self.LastNode:return False
        self.LastNode = root.val  # 将当前结点的值赋值给self.LastNode(即为中间变量)
        if not(self.isValidBST(root.right)):return False  # 递归调用右子树,最开始判断右子树的最左叶子结点是否比中间变量小,即通过上面的递归调用左子树判断
        return True
发布了5 篇原创文章 · 获赞 4 · 访问量 640

猜你喜欢

转载自blog.csdn.net/weixin_43975924/article/details/90709058