LeetCode202004012

 

CanChen ggchen@mail.ustc.edu.cn


Recently I am reviewing leetcode top100 liked problems that I have solved before and I find the most important thing is intuition, which means you need to come up with the solution by yourself step by step.

13.Given a binary tree, flatten it to a linked list in-place.

This is in fact in-order traverse. For a parent, I first moved its right child to the child of the left child and then move its left child to the parent's right child. This is very intuitive after I draw some examples.
Keyword:Recursive

14.Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

We can use the array's index as connecting information to construct a linked list with a circle. The duplicate element is the entry and with the help fast and slow pointer we can solve this problem easily.

I also came up with another interesting solution. From the left to right, we visit every element and use this element as an index. Then we set the element at the index as its negative. For duplicate element as an index, it will set the element as negative first and then positive again. When detecting this change, we can find the duplicate one.
Keyword: Fast and slow pointer

15.Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array.

The solution is quite similar to 14.

16.Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

For binary tree problems, we neeed to consider Recursive method first. For a parent node, here are two situations, connected by two children to serve the final diameter, or connected by one child to serve part of the final diameter.
Keyword: Recursive

17.There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Keyword: Topological sorting

18.Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

The best solution is quite tricky which uses bit computing. We only need to compute the calculation times of i = i &(i - 1) until i=0.

Keyword: bits computing

19.Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Quite easy and just get the sum between the current node and its right node.
Keyword: Recursive

20.Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water

This is quite similar to P3, both asking for the max area of rectangle. The different place is that P3 relies on the lowest bound of every bar in the rectangle while this problem focus on the smaller vertical line of the two sides, just ignoring the interims.

For this problem, we use the two pointer method, left and right.
When the height of the left is smaller than that of the right, we need to move left to the next one since moving right will not give us a bigger area than now.

Keyword: two pointers

21.Given preorder and inorder traversal of a tree, construct the binary tree.

Traditional problem in the textbook.
Keyword: Recursive

22.Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Set the target as root node and use BFS to minus one element everytime. The only thing we need to consider is to sort the array and use an element no large than the previous one. This could reduce much redundancy.

This problem can also solved by DP but many paths needed to be recorded and the cost is huge.

Keyword: BFS

23.You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

This is a traditional DP problem. DP[target]=num means that to reach target we need at least "num" numbers.

Also, like P22, BFS can solve this problem.

Keyword: DP

24.Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. Find the maximum coins you can collect by bursting the balloons wisely.

This is a very hard problem for me and I can not find the solution at first.
The best solution is wonderful. Just consider from at last point we choose and then this point can divide this array into two parts, the left and the right. The two parts do not influence each other since this dividing point is chosen after we get the result from the left side and the right side. So the result from left to right can be computed by all subproblems which choose the index i between left and right exclusively.

Keyword: DP

25.Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

For each node, it has two options, to accept its parent as part of the path or not to accept. For the first case, then you should know the max sum ended at the parent so every node should update this formation--max sum ended at itself from top to down. Actually, here comes two options, only the node itself or the previous path sum plus the node.For the second case, just itself.

Keyword: Recursive

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

Keyword: BFS

27.Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

For this problem, we first compute all twoSum situations and then use Hash. One thing to remember is not to use the same element twice in a triplet.
Keyword: Hash

28.Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

This is a DP problem where each word can break into two parts.
The left part is a subproblem while the right part can be solved by a hash dic.
Keyword: DP

29.Given a binary tree, determine if it is a valid binary search tree (BST).

Keyword: Inorder traverse

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

Keyword: Stack

31.Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n

In fact, inorder and preorder together define a BST. We only need to find the number of possible preorder sequences.
Everytime I chose an element as the root, the left and the right become two subproblems. We can use DP.
Keyword: DP

32.A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Just use a line to scan every possible interval.
Keyword: Line scan

33.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.

Just input two root and use the Recursive method.
Keyword: Recursive

34.Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree scould also be considered as a subtree of itself.

Keyword: Recursive

35.Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

First we need to compute the accumulation sum and this becomes a twoSum question.

Keyword:Hash

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

Keyword: XOR

37.Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length.

From left to right, we find the first unusual number and the same thing is done from right to left. Between the two numbers, we need to find the max and min. According to min, we need to find the first element larger than min from left to right. The same is done from right to left.
Keyword: two pointers

38.Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

In fact, given an element, if it is larger than nums[0], then the right part can be set as all inf positive or the left part should be set as all inf negative. To be specific, everytime we get a middle index, we can compare its value with nums[0]. The middle value remains unchanged if it is on the same side with target.
Keyword: Binary Search

39.Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

We should analyse this problem first then traverse the matrix from the top right corner. Decide whether to go down or left then.

40.here give a common method to solve the image rotation problems.

clockwise rotate: first reverse up to down, then swap the symmetry
anticlockwise rotate: first reverse left to right, then swap the symmetry.

41.Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Keyword:BFS

42.Given an input string (s) and a pattern (p), implement regular expression matching with support for . and *. . Matches any single character. * Matches zero or more of the preceding element.

let D[i][j] means whether s[0:i] could be represented by p[0:j] and this becomes a DP problem.
Keyword: DP

43.You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

This is very similiar to P16.

44.Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

This problem is very similar to target sum problem. The only different thing is that here we can not use the same element twice. So for every num in nums, we need to compute dp[i]=dp[i]||dp[i-num] , for i from target to num. This can avoid repeating elements.

Keyword: DP

45.Given a singly linked list, determine if it is a palindrome

Keyword: Fast and slow pointer

46.Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Just try to move the non-zero num to the most left part.

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

This method is quite tricky. Here we use a link2nextmin array.
For instance, if current min index is i, then the second min index is link2nextmin[i]. To construct the link2nextmin array, we need to record the current min and its index. When a new element is pushed into the stack, we need to update the link2nextmin array if the element is smaller than the top.

48.Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree

Keyword: Recursive

 

posted @ 2020-04-12 19:30  Klaus-Chen  阅读(92)  评论(0编辑  收藏  举报