leetcode刷题记录

  1. Data structure:
    list, set, dict, heapq, collections.Counter, collections.deque, queue.PriorityQueue, collections.defaultdict

  2. Union Find:

    1. Friend Circles:
      Union Find. I used weighting and path compression.
  1. Hash:
    1. 3Sum
      Divide and conquer. Divide it into n two-sum problems. To optimize, you can first sort the array, and traverse it one by one for all the negative ones.
      For each two-sum problems, you only need to restore one element of the pair in the set. If it is already in the set, add these three numbers to the final answer, which is a set so we can avoid duplicate ones. If it is not in the set, add its mirror item to the set.
    1. Longest Consecutive Sequence
      Use Hash (in python it is set) to quickly judge whether an element is in a set. Start from the beginning of each sequence.
    1. K-diff Pairs in an Array
      Advanced version of two sum. Use a dict and a set. Only use one side of the pair. Go through the list twice so that the order you meet the two elements in a pair won’t matter. Use the index as the value in the dict to avoid the case k==0.
    1. Majority Element
      Hash is too space consuming for this problem. You should use Boyer-Moore Voting Algorithm: you can consider the majority as one type, and the others as the other type, and then use a counter to count the numbers last majority appears. Since the majority appears more than N/2, you will find it at last.
    1. Contains Duplicate II
      Use dictionary. This question belongs to the duplicate number kind of problem. But the range of numbers is not restricted to 1~n. And there is an additional condition of k difference. So the space complexity is hard to be reduced to O(1).
    1. Path Sum III
      This is essentialy a k-diff problem, but on prefix sums instead of array elements. This kind of problem uses prefix sum and hashmap a lot. You can use hashmap to store all the prefix sum and their frequency, and then search for the current prefix sum - sum.
    1. Distribute Candies
      Use set. For this kind of problems, you need to memorize every number you meet, and since they are not bounded in a fixed range, you should use a hashmap to memorize them.
    1. Group Anagrams
      Use a dict to store frequency lists of 26 letters. Using this list is much better than storing all the variations of an anagram.
  1. DFS:
    O(n) time, O(logn) space.
    You can use recursion or iteration(stack, i.e. list in python).
    Be careful that you shouldn’t use elif when you want to try all the directions in your dfs function.
    1. Knight Probability in Chessboard
      DFS is used by recursion. DP is too time consuming for it.
    1. Friend Circles:
      It can be done with union find or DFS.
    1. Validate Binary Search Tree
      DFS on the tree. Memorize the previous nodes’ ranges.
    1. Unique Paths III
      DFS function’s parameter can have depth. You can flag the current node to avoid repeting it in the following recursions. You can count the total depth to judge when it goes through all the elements.
    1. Number of Islands
      DFS.
    1. Binary Tree Preorder Traversal
      Recurion or iteration.
      pace: pop, append, append
    1. Binary Tree Inorder Traversal
      Recurion or iteration.
      pace: append,append,…append,pop,append,append,…,append
    1. Binary Tree Postorder Traversal
      Recurion or iteration.
      Reverse preorder.
      If you need to transform a recursion to a postorder traversal for dfs more complex than this problem, you can restore some key variables as a list in each position of the stack.
    1. Distribute Coins in Binary Tree
      Assume the root has infinite coins, count how many coin moves the left subtree and right subtree need separately.
    1. Zuma Game
      It has some problems in its test cases.
    1. Generate Parentheses
      Cut branches when there are only right parentheses.
    1. Symmetric Tree
      DFS with two mirror nodes.
    1. Convert Sorted Array to Binary Search Tree
      Recursion. Use the medians.
    1. Invert Binary Tree
      Directly exchange the child nodes.
    1. Combination Sum
      Recursion is ok. While loop should also work?
      In recursion, you can use a pointer to indicate the head of the list, and conduct a for loop to traverse from the current head to the tail of the list.
    1. Combination Sum II
      Recursion. Dealing with the repetitive numbers is a tricky part.
    1. Permutations
      Recursion. There are two ways: 1. Traverse the list and use a set to store all the elements you have met. 2. Traver a dict that stores whether a nums have been used.
    1. Permutations II
      Recursion. There are two ways: 1. Traverse the list and use a set to store all the elements you have met. You also need a variable to store the last number you have met in the for loop. 2. Traver a dict that stores how many times of a number are left to use.
      The second way is better.
    1. Longest String Chain
      Memoization. DP.
  1. BFS:
    O(n) time, O(n) space for one directional BFS, O(n^(0.5)) space for bi-directional BFS.
    How to create the graph is the core.
    See 2470 below for doing operations for each level after finishing them while maintainign only one queue.
    1. Word Ladder
      The core is to create the words graph by using underdetermined words with O(Nlen(word)) instead of the original words with O(NN*len(word).
      You can also use bi-directional way to solve BFS. Since it may lead to exponential increase if each element has same branching factors.
    1. Maximum Depth of Binary Tree
      Simple BFS.
    1. Shortest Path in Binary Matrix
    1. Minimum Number of Operations to Sort a Binary Tree by Level
      Two steps

你可能感兴趣的:(Leetcode,算法,数据结构)