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

猜你喜欢

转载自blog.csdn.net/weixin_42307828/article/details/82937419