Leetcode 817(Description和Solution的思路不一致)
来源:5-1 Leetcode中和链表相关的问题
weibo_新的旅涂_0
2018-08-08
https://leetcode.com/problems/linked-list-components
We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
Example 1:
Input: head: 0->1->2->3
G = [0, 1, 3]Output: 2Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
Example 2:
Input: head: 0->1->2->3->4
G = [0, 3, 1, 4]Output: 2Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
Solution:
Algorithm
Scanning through the list, if node.val is in G and node.next.val isn't (including if node.next is null), then this must be the end of a connected component.
For example, if the list is 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7, and G = [0, 2, 3, 5, 7], then when scanning through the list, we fulfill the above condition at 0, 3, 5, 7, for a total answer of 4.
总结:Description中寻找的是连通的结果,而Solution中寻找的是非连通的结果。
1回答
-
看了一遍。没有问题。Description中问题问的是有多少个联通分量(connected component)
对于第一个例子,
head: 0->1->2->3
G = [0, 1, 3]得到的两个联通分量是:
head: 【0->1】->2->【3】
对于第二个例子,
head: 0->1->2->3->4
G = [0, 3, 1, 4]得到的两个联通分量是:
head: 【0->1】->2->【3->4】
对于Solution中给出的例子:
head:0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
G = [0, 2, 3, 5, 7]
得到的四个联通分量是:
head: 【0】 -> 1 ->【 2 -> 3】 -> 4 ->【 5】 -> 6 ->【7】
212018-08-08
相似问题