首页 > 其他分享 >817. Linked List Components

817. Linked List Components

时间:2023-02-04 00:45:16浏览次数:45  
标签:head val graph List linked connected Components visited Linked

package LeetCode_817

/**
 * 817. Linked List Components
 * https://leetcode.com/problems/linked-list-components/
 * You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.

Example 1:
Input: head = [0,1,2,3], nums = [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], nums = [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.

Constraints:
The number of nodes in the linked list is n.
1 <= n <= 10^4
0 <= Node.val < n
All the values Node.val are unique.
1 <= nums.length <= n
0 <= nums[i] < n
All the values of nums are unique.
 * */

//Definition for singly-linked list.
class ListNode(var `val`: Int) {
    var next: ListNode? = null
}

class Solution {
    /**
     * Solution: Build graph + DFS to find out connected components;
     * Time complexity:O(n), Space complexity:O(n);
     * */
    fun numComponents(head: ListNode?, G: IntArray): Int {
        //1. build undirected graph by ListNode, u->v, if both u,v in G
        var head_ = head
        val graph = HashMap<Int, ArrayList<Int>>()
        while (head_?.next != null) {
            val u = head_.`val`
            val v = head_.next?.`val` ?: -1
            if (G.contains(u) && v != -1 && G.contains(v)) {
                graph.putIfAbsent(u, ArrayList())
                graph.putIfAbsent(v, ArrayList())
                graph.get(u)?.add(v)
                graph.get(v)?.add(u)
            }
            head_ = head_.next
        }
        var result = 0
        val visited = HashSet<Int>()
        //2. the count of connected components is the use times of DFS,
        // because after DFS all node will be traversed, so result++.
        for (item in G) {
            if (visited.contains(item)) {
                continue
            }
            dfs(item, graph, visited)
            result++
        }
        return result
    }

    private fun dfs(current: Int, graph: HashMap<Int, ArrayList<Int>>, visited: HashSet<Int>) {
        if (visited.contains(current)) {
            return
        }
        visited.add(current)
        if (graph.get(current) != null) {
            for (next in graph.get(current)!!) {
                dfs(next, graph, visited)
            }
        }
    }
}

 

标签:head,val,graph,List,linked,connected,Components,visited,Linked
From: https://www.cnblogs.com/johnnyzhao/p/17090762.html

相关文章

  • Java Collection接口下的“ List 集合” 与 “ Set 集合 ”
    JavaCollection接口下的“List集合”与“Set集合”每博一文案一个人最好的底牌,就这两个字:靠谱,是最高级的聪明。师父说:人生一回,道义一场,你对人对事的态度,藏......
  • flutter:使用listview之一(flutter 3.7.0)
    一,flutter代码1,page/list.dartimport'package:flutter/material.dart';import'package:dio/dio.dart';import'package:demolist/model/list_goods.dart';import......
  • java list<对象>根据某个字段分组
    前言仅供学习参考,不保证性能问题其中的实体类改成你自己的实体类代码/***根据某个字段进行分组,分组后遍历方法*<p>*Map<String,List<MyDoma......
  • Java中ArrayList的扩容机制
    1.简介publicclassArrayList<E>extendsAbstractList<E>implementsList<E>,RandomAccess,Cloneable,java.io.SerializableArrayList的底层基于数组来实现,故......
  • 面试题之List集合如何实现去重?
    关于List集合去重的问题其实是很简单的不过简单的问题要尽量考虑全面一些!要考虑JDK1.8的新特性实现List集合去重的三种方式:1、方式一直接定义一个方法循环遍历判断......
  • java Set和List的区别
    1、重复。Set不允许重复插入。2、插入顺序。Set不能保证插入顺序。3、null元素。4、实现类。list方法常用的实现类:ArrayList、LinkedList和Vector。Set:HashSet、Lin......
  • TreeMap,HashMap,LinkedHashMap区别
    TreeMap,HashMap,LinkedHashMap之间的区别和TreeSet,HashSet,LinkedHashSet之间的区别相似。TreeMap:内部排序,内部使用了红黑树排序HashMap:无序。LinkedHashMap:顺序存取,内部是单......
  • Java - 一道关于Arrays.asList的题目
    题目有这样一道有趣的题目:finalint[]test=newint[]{1,2,3,4};finalInteger[]test2=newInteger[]{1,2,3,4};finalListlist1=Arrays.asList(test);finalListl......
  • List<Object> 根据对象中的属性过滤数据
    一.代码块publicstaticvoidmain(String[]args){//1.测试数据创建UserEntityuser1=UserEntity.builder().id(1).name("张三").sex(0).build(......
  • 春哥博客 - ArrayList集合
    staticvoidMain(string[]args){//集合:很多数据的一个集合//集合的好处:长度可以任意改变,类型随便ArrayListlist=n......