817. 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: 2 Explanation: 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: 2 Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
Note:
- If
N
is the length of the linked list given byhead
,1 <= N <= 10000
. - The value of each node in the linked list will be in the range
[0, N - 1]
. 1 <= G.length <= 10000
.G
is a subset of all values in the linked list.
解题思路
首先创建一个长度为N的空列表,该链表中第i个元素(0<=i<=N-1)存储的值为:
True:如果i+1的值在G中
False:如果i+1的值不在G中
遍历链表head,由于有了前面的空列表,因此对于每个在链表中的值,可以在O(1)时间内判断其是否在G中(相当于哈希),对于每一个循环,相应的设置result(需要返回的结果)和flag(链表中前面那一个值是否在G中)的值,最后便能得到结果,时间复杂度为仅为O(n)
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def numComponents(self, head, G):
"""
:type head: ListNode
:type G: List[int]
:rtype: int
"""
result = 0
flag = False
n = 0
temp = head
while(temp!=None):
n+=1
temp = temp.next
e = [False]*n
for i in range(len(G)):
e[G[i]-1] = True
while(head!=None):
if e[head.val-1]==True:
if flag==False:
result+=1
flag = True
else:
flag = True
else:
flag = False
head = head.next
return result
心得与体会
刚开始做的时候,在对链表head的遍历中,对于每一个循环都在G中进行查找,此时间复杂度为O(n^m),后来创建了一个空列表,相当于一个哈希表,能将时间复杂度降低到O(n),而不必每次都在G中进行循环查找,仅用O(1)时间就够了,通过这个题目体会到了哈希表带来的便利性。