leetcode hot100 easy

文章主要介绍了LeetCode上的一系列与数组和链表相关的算法问题,包括找到数组中两数之和、检查括号的有效性、合并两个已排序的链表、爬楼梯问题以及二叉树的中序遍历等。每个问题都给出了Python代码实现,并分析了时间复杂度和空间复杂度。
摘要由CSDN通过智能技术生成

两数之和 two-sum

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

链接:https://leetcode.cn/problems/two-sum

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for index, num in enumerate(nums):
            if target - num in dic:
                return [index, dic[target - num]]
            dic[num] = index
        return []

time: O n
size: O 1

Valid Parentheses

https://leetcode.cn/problems/valid-parentheses/

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {')':'(',']':'[','}':'{'}
        for char in s:
            if char in mapping:
                if not stack or stack.pop() != mapping[char]:
                    return False
            else:
                stack.append(char)

        return not stack

time: O n
size: O m (m = 左括号的数量,一般来说比n小)

Merge Two Sorted Lists

https://leetcode.cn/problems/merge-two-sorted-lists/

  • 链表需要自定义
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # if not list1:
        #     return list2
        # if not list2:
        #     return list1
        
        dummy = curr = ListNode(0)
        while list1 and list2:
            if list1.val < list2.val:
                curr.next = list1
                list1 = list1.next
            else:
                curr.next = list2
                list2 = list2.next
            curr = curr.next
        curr.next = list1 or list2
        return dummy.next

time: O n
size: O 1

Climbing Stairs

https://leetcode.cn/problems/climbing-stairs/

class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 1:
            return 1 

        dp = [0] * (n + 1)
        dp[1] = 1
        dp[2] = 2
        for i in range(3,n+1):
            dp[i] = dp[i-2] + dp[i-1]
        return dp[n]

time: O n
size: O n

Binary Tree Inorder Traversal

https://leetcode.cn/problems/binary-tree-inorder-traversal/?favorite=2cktkvj

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def inorder(root):
            if root == None:
                return 
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)

        inorder(root)
        return res

time: O n
size: O h (树的高度)

Symmetric Tree

https://leetcode.cn/problems/symmetric-tree/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def isMirror(left,right):
            if not left and not right:
                return True
            if not left or not right:
                return False
            return left.val == right.val and isMirror(left.left,right.right) and isMirror(left.right,right.left)
        return isMirror(root,root)

time: O n
size: O h (树的高度)

Maximum Depth of Binary Tree

https://leetcode.cn/problems/maximum-depth-of-binary-tree/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

time: O n
size: O h (树的高度) 最大可能为 n

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = []
        queue.append((1,root))
        depth = 1

        while queue:
            cur_depth,cur_node = queue.pop(0)
            depth = max(depth,cur_depth)
            if cur_node.left:
                queue.append((depth+1,cur_node.left))
            if cur_node.right:
                queue.append((depth+1,cur_node.right))
        return depth
                

time: O n
size: O n (节点个数)

Best Time to Buy and Sell Stock

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) < 2:
            return 0
        min_price  = prices[0]
        max_profit = 0
        for cur_price in prices:
            if cur_price < min_price:
                min_price = cur_price
            else:
                max_profit = max(max_profit, cur_price - min_price)
        return max_profit

贪心 greedy

time: O n
size: O 1

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) < 2:
            return 0
        dp = [0] * len(prices)
        max_profit = 0

        for i in range(1,len(prices)):
            dp[i] = max(dp[i-1] + prices[i] - prices[i-1],0)
        # print(dp)
        return max(dp)

dp[i] 定义: 在 i 天卖出的最大利润.相当于 prices[i] - prices[0-i区间的最小值index]

time: O n
size: O n

Single Number

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for num in nums:
            result ^= num
        return result

异或符号为:^ 。 0与任何数异或都为任何数本身。 相同为0,不同为1。

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = nums[0]
        for i in range(1,len(nums)):
            res ^= nums[i]
        return res

time: O n
size: O 1

10. Linked List Cycle

https://leetcode.cn/problems/linked-list-cycle/

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

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

time: O n
size: O 1

Intersection of Two Linked Lists

https://leetcode.cn/problems/intersection-of-two-linked-lists/

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        pa = headA
        pb = headB
        lena = lenb = 0
        
        while pa:
            lena += 1
            pa = pa.next
        while pb:
            lenb += 1
            pb = pb.next
        
        pa = headA
        pb = headB

        if lena > lenb:
            for i in range(lena - lenb):
                pa = pa.next
        else:
            for i in range(lenb - lena):
                pb = pb.next
        
        while pa != pb:
            pa = pa.next
            pb = pb.next
        
        return pa
        

time: O m+n 两条链表长度
size: O 1

Majority Element

https://leetcode.cn/problems/majority-element/

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = 0
        candidate = 0
        for num in nums:
            if count == 0:
                candidate = num 
            count += (1 if candidate == num else -1)
        return candidate

此消彼长 消消乐

time: O n
size: O 1

Reverse Linked List

https://leetcode.cn/problems/reverse-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        curr = head
        while curr:
            curr_next = curr.next
            curr.next = prev
            prev      = curr
            curr      = curr_next
        return prev

time: O n
size: O 1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next      = None 
        return p

time: O n
size: O n

Invert Binary Tree

https://leetcode.cn/problems/invert-binary-tree/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        left  = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left  = right
        root.right = left
        return root

time: O n
size: O h 树高

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return root
        queue = [root]
        while queue:
            node = queue.pop(0)
            node.left, node.right = node.right, node.left
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return root

bfs 相对递归,队列空间最多占用 n/2 ,对于不平衡二叉树效果好于栈

time: O n
size: O n

Palindrome Linked List

https://leetcode.cn/problems/palindrome-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        prev = None
        while slow:
            slow_next = slow.next
            slow.next = prev
            prev      = slow
            slow      = slow_next
        
        while prev:
            if prev.val != head.val:
                return False
            prev = prev.next
            head = head.next
        
        return True

快慢指针遍历,slow就位后反转后面链表,再和前面的链表进行比较

time: O n
size: O 1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        stack = []
        slow = fast = head
        while fast and fast.next:
            stack.append(slow.val)
            slow = slow.next
            fast = fast.next.next
        
        # 对于奇数长度的链表,跳过中间点
        if fast:
            slow = slow.next

        while slow:
            if slow.val != stack.pop():
                return False
            slow = slow.next

        return True

time: O n
size: O n

Move Zeroes

https://leetcode.cn/problems/move-zeroes/

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zero_index = 0
        for index in range(len(nums)):
            if nums[index] != 0:
                nums[index], nums[zero_index] = nums[zero_index], nums[index]
                zero_index += 1
         

time: O n
size: O 1

Counting Bits

https://leetcode.cn/problems/counting-bits/

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(1,n+1):
            ans[i] = ans[i & (i - 1)] + 1
        return ans

i & (i - 1) 位操作用于寻找前一个2次幂

比特位1的个数等于前一个2次幂的比特位1的个数再加1

time: O n
size: O n

Find All Numbers Disappeared in an Array

https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            index_range_1_n = abs(nums[i]) - 1
            nums[index_range_1_n] = -abs(nums[index_range_1_n])
        
        res = []
        for i in range(len(nums)):
            if nums[i] > 0:
                res.append(i + 1)

        return res

time: O n
size: O n

Hamming Distance

https://leetcode.cn/problems/hamming-distance/

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        xor   = x ^ y
        count = 0
        while xor:
            count += xor & 1
            xor = xor >> 1
        return count

异或计算xy不同的比特位置位1,然后就是计算比特位1的个数,使用 & 1 计数;

xor = xor >> 1 需要赋值,不然超时

Diameter of Binary Tree

https://leetcode.cn/problems/diameter-of-binary-tree/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        self.ans = 0

        def dfs(root):
            if not root:
                return 0
            L = dfs(root.left)
            R = dfs(root.right)
            self.ans = max(self.ans, L + R)
            return max(L,R) + 1
        
        dfs(root)
        return self.ans

time: O n
size: O h

21. Merge Two Binary Trees

https://leetcode.cn/problems/merge-two-binary-trees/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root1:
            return root2

        if not root2:
            return root1
        
        root1.val += root2.val

        root1.left  = self.mergeTrees(root1.left,  root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)

        return root1

time: O n
size: O h

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值