Files
LeetCode-Go/leetcode/0817.Linked-List-Components/817. Linked List Components.go
2020-08-07 17:06:53 +08:00

48 lines
742 B
Go

package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func numComponents(head *ListNode, G []int) int {
if head.Next == nil {
return 1
}
gMap := toMap(G)
count := 0
cur := head
for cur != nil {
if _, ok := gMap[cur.Val]; ok {
if cur.Next == nil { // 末尾存在,直接加一
count++
} else {
if _, ok = gMap[cur.Next.Val]; !ok {
count++
}
}
}
cur = cur.Next
}
return count
}
func toMap(G []int) map[int]int {
GMap := make(map[int]int, 0)
for _, value := range G {
GMap[value] = 0
}
return GMap
}