leetcode简单题21-40(python)

100. Same Tree(e-21)

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

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

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
       
        if not p or not q:
            return p==q
        return p.val ==q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

101. Symmetric Tree(e-22)

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

class Solution:
    def isSymmetric(self, node):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(root, mirror):
            if not root and not mirror:
                return True
            if root and mirror and root.val == mirror.val:
                return helper(root.left, mirror.right) and helper(root.right, mirror.left)
            return False
        return helper(node, node)

104. Maximum Depth of Binary Tree(e-23)

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

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

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right))+1

107. Binary Tree Level Order Traversal II(e-24)

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7]

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        ans=[[root.val]]
        queue=deque([root])
        while queue:
            levelans=[]
            for _ in range(0,len(queue)):
                root=queue.popleft()
                if root.left:
                    levelans.append(root.left.val)
                    queue.append(root.left)
                if root.right:
                    levelans.append(root.right.val)
                    queue.append(root.right)
            if levelans:
                ans.append(levelans)
        return ans[::-1]
                    

108. Convert Sorted Array to Binary Search Tree(e-25)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

class Treenode:
    def __init__(self,x):
        self.val=next
        self.left=None
        self.right=None
    
class Solution:
    def sortedArrayToBST(self, nums):
        if nums:
            midp=int(len(nums)/2)
            mid=nums[midp]
            root=Treenode(mid)
            root.left=self.sortedArrayToBST(nums[:midp])
            root.right=self.sortedArrayToBST(nums[midp+1:])
            return root

110. Balanced Binary Tree(e-26)

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

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

class Solution:
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def dfs(p):
            if not p:
                return 0
            left=dfs(p.left)
            right=dfs(p.right)
            if left == -1 or right == -1:
                return -1
            if abs(left - right) > 1:
                return -1
            return 1+max(right, left)
        if dfs(root) == -1:
            return False
        return True

111. Minimum Depth of Binary Tree(e-27)

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

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

class Solution:
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        left=self.minDepth(root.left)
        right=self.minDepth(root.right)
        if not left and not right:
            return 1
        elif not left:
            return right+1
        elif not right:
            return left+1
        else:
            return min(left, right) + 1

112. Path Sum(e-28)

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

from collections import deque
class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root:
            queue = deque([(root, root.val)])
            while queue:
                p, s = queue.popleft()
                left, right = p.left, p.right
                if left:
                    queue.append((p.left, s+p.left.val))
                if right:
                    queue.append((p.right, s+p.right.val))
                if not left and not right and s == sum:
                    return True
            return False
        return False

118. Pascal's Triangle(e-29)

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

class Solution:
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        ans=[[1]*n for n in range(1, numRows+1)]
        for i in range(1,numRows+1):
            for j in range(0, i-2):
                ans[i-1][1+j]=ans[i-2][j]+ans[i-2][j+1]
        return ans

119. Pascal's Triangle II(e-20)

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        rownum=rowIndex+1
        currow=[1]
        if rownum==1:
            return currow
        if rownum>0:
            currow=[1]
            for index in range(rownum):
                prerow=currow
                currow=[1]
                for j in range(index-1):
                    currow.append(prerow[j]+prerow[j+1])
                currow.append(1)
        return currow

121. Best Time to Buy and Sell Stock(e-31)

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        ans=0
        pre=prices[0]
        for i in range(1,len(prices)):
            pre = min(pre, prices[i])
            ans=max(prices[i] - pre, ans)
        return ans

122. Best Time to Buy and Sell Stock II(e-32)

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        ans=0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                ans+=prices[i] - prices[i-1]
        return ans

125. Valid Palindrome(e-33)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        start, end = 0, len(s) - 1
        while start < end:
            if not s[start].isalnum():
                start += 1
                continue
            if not s[end].isalnum():
                end -= 1
                continue
            if s[start].lower() != s[end].lower():
                return False
            start += 1
            end -= 1
        return True
        

136. Single Number(e-34)

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res=0
        for i in nums:
            res ^= i
        return res

141. Linked List Cycle(e-35)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast=slow = head
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
            if slow == fast:
                return True
        return False

155. Min Stack(e-36)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
    class MinStack(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.stack = []
    
        def push(self, x):
            """
            :type x: int
            :rtype: void
            """
            if not self.stack:
                self.stack.append((x, x))
            else:
                self.stack.append((x, min(x, self.stack[-1][-1])))
            
    
        def pop(self):
            """
            :rtype: void
            """
            self.stack.pop()
    
        def top(self):
            """
            :rtype: int
            """
            return self.stack[-1][0]
    
        def getMin(self):
            """
            :rtype: int
            """
            return self.stack[-1][1]
    
    
    # Your MinStack object will be instantiated and called as such:
    # obj = MinStack()
    # obj.push(x)
    # obj.pop()
    # param_3 = obj.top()
    # param_4 = obj.getMin()

     

160. Intersection of Two Linked Lists(e-37)

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

 

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def getIntersectionNode(self, headA, headB):
            if headA is None or headB is None:
                return None
            pa = headA
            pb = headB
            while pa is not pb:
                pa = headB if pa is None else pa.next
                pb = headA if pb is None else pb.next
            return pa

    167. Two Sum II - Input array is sorted(e-38)

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        start, end=0,len(numbers)-1
        while start<end:
            s=numbers[start]+numbers[end]
            if s>target:
                end-=1
            elif s<target:
                start+=1
            else:
                return (start+1, end+1)
                
            

168. Excel Sheet Column Title(e-39)------不懂

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

class Solution(object):
  
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = ''
        while n:
            res = chr((n-1)%26 + 65) + res
            n = (n-1) / 26
        return res

169. Majority Element(e-40)

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums_set=set(nums)
        for i in nums_set:
            if nums.count(i) > len(nums)/2:
                return i

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: LeetCode是一个优秀的在线编程平台,提供了丰富的算法和数据结构目供程序员练习。其中的简单大多可以用Python语言编写,下面为您提供几个常见目的Python版本答案。 1. 两数之和(Two Sum) 目描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 Python版本答案: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if target - x in d: return [d[target - x], i] d[x] = i 2. 反转字符串(Reverse String) 目描述:编写一个函数,其作用是将输入的字符串反转过来。 Python版本答案: class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 3. 回文数字(Palindrome Number) 目描述:判断一个整数是否是回文数,例如:121是回文数,-121不是回文数。 Python版本答案: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False if x == 0: return True str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True 以上只是这几个简单目的Python版本答案,实际上LeetCode上还有很多其他编程语言编写的优秀答案,需要程序员们自己去探索和实践。 ### 回答2: Leetcode是一个流行的在线编程库,提供了许多关于算法和数据结构的目,难度从简单到困难不等。Python是一种易学易用的编程语言,备受程序员欢迎。因此,许多程序员使用Python来解决Leetcode的编程问。下面我将提供一些Python版本的Leetcode简单的答案。 1. 两数之和 目描述:给定一个整数数组和一个目标值,在数组中找到两个数之和等于目标值。 解思路:使用哈希表来存储数组中每个元素的值和索引,然后遍历每个元素时,查找目标值减去当前元素的值是否在哈希表中,如果存在,返回两个值的索引。 Python代码: def twoSum(nums, target): hash_table = {} for i, num in enumerate(nums): complement = target - num if complement in hash_table: return hash_table[complement], i hash_table[num] = i nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target)) # Output: (0, 1) 2. 路径总和 目描述:给定一棵二叉树和一个目标值,判断是否存在从根节点到叶节点的路径,使得路径上所有节点的值相加等于目标值。 解思路:遍历二叉树的所有路径,判断路径上所有节点的值相加是否等于目标值。 Python代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(root, sum): if not root: return False if not root.left and not root.right and root.val == sum: return True return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) sum = 22 print(hasPathSum(root, sum)) # Output: True 3. 最大子序和 目描述:给定一个整数数组,找到一个具有最大和的子数组,返回该子数组的和。 解思路:使用动态规划,定义状态dp[i]表示以第i个数结尾的最大子数组和,则状态转移方程为dp[i] = max(dp[i-1] + nums[i], nums[i])。 Python代码: def maxSubArray(nums): if not nums: return 0 n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp) nums = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(nums)) # Output: 6 总结:以上是三个Python版本的Leetcode简单的答案,它们涉及到哈希表、二叉树、动态规划等算法和数据结构。这些目既考验了程序员的基本功,又是训练算法思维的好工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值