leetcode306
题目要求
1 | Additive number is a string whose digits can form additive sequence. |
1 | Additive number is a string whose digits can form additive sequence. |
1 | Say you have an array for which the ith element is the price of a given stock on day i. |
和前面几题相比,这题还增加了一个限制条件,也就是说我们在抛出股票之后,还需要冷却一天才可以买入下一只股票。那么我们进行什么样的操作才能使收益最大呢?
1 | The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. |
即如何从树中选择几个节点,在确保这几个节点不直接相连的情况下使其值的和最大。
1 | Given a nested list of integers, implement an iterator to flatten it. |
假设有一个嵌套形式的数组,要求按照顺序遍历数组中的元素。
1 | Given a non-empty array of integers, return the k most frequent elements. |
假设有一个非空的整数数组,从中获得前k个出现频率最多的数字。
1 | For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. |
在无向图的生成树中,我们可以指定任何一个节点为这棵树的根节点。现在要求在这样一棵生成树中,找到生成树的高度最低的所有根节点。
其实,决定一棵树的高度往往是树中的最长路径,只有我们选择最长路径的中间点才能够尽可能减少树的高度。那么我们如何找到所有的中间节点呢?
当出发点只有两个时,我们知道中间节点就是从出发点同时出发,当二者相遇或者二者只间隔一个位置是所在的点就是两个出发点的重点。那么多个出发点也是同样的道理,每个人从各个出发点出发,最终相遇的点就是我们所要找的中间点。
这题的思路有些类似于拓扑排序,每次我们都会去除所有入度为0的点,因为这些点肯定是叶节点。然后不停的往中间走,直到剩下最后一个叶节点或是最后两个叶节点。
1 | 0 |
这个图中删除所有入度为0的点就只剩下1,因此我们知道1一定就是我们所要求的根节点
这一种解法着重强调了利用图论中的数据结构来解决问题。这里我们采用图论中的邻接表来存储图中的点和边。
然后利用邻接表的相关属性来判断当前节点是否是叶节点。
1 | public List<Integer> findMinHeightTrees(int n, int[][] edges) { |
这里使用degree数组存储每个顶点的度数,即连接的变数。度数为一的顶点就是叶节点。再用connected存储每个顶点所连接的所有边的异或值。
这里使用异或的原因是对同一个值进行两次异或即可以回到最初值。
1 | public List<Integer> findMinHeightTrees2(int n, int[][] edges) { |
1 | You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs. |
假设现在有两个杯子,每个杯子分别最多可以装x和y升水,假设现在水的供应量是无限的,问是否有可能用这两个杯子共同承装z升水,可以用两个杯子执行的操作如下:
比如,如果现在两个杯子A和B分别能装3升水和5升水,需要在两个杯子中共装4升水。我们可以找到这样一个序列满足题目要求:
1 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. |
假设有一个无序的数组,如果数组中从左到右存在三个由小到大的数字,则返回true。否则返回false。
题目的额外要求是:O(n)的时间复杂度和O(1)的空间复杂度
1 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. |
假设有一组字母和一组从杂志中获取的字母,问是否能够用从杂志中获取的字母构成想要的那组字母,要求每个单词只能使用一次。