Skip to content

Latest commit

 

History

History
62 lines (50 loc) · 1.46 KB

_817. Linked List Components.md

File metadata and controls

62 lines (50 loc) · 1.46 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 04, 2024

Last updated : July 04, 2024


Related Topics : Array, Hash Table, Linked List

Acceptance Rate : 57.15 %


Solutions

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int numComponents(ListNode head, int[] nums) {
        HashSet<Integer> ref = new HashSet<>();
        for (int i : nums) {
            ref.add(i);
        }

        int counter = 0;
        boolean previousIsComponent = false;
        while (head != null) {
            if (ref.contains(head.val)) {
                if (!previousIsComponent) {
                    counter++;
                }
                previousIsComponent = true;
            } else {
                previousIsComponent = false;
            }

            head = head.next;
        }
        return counter;
    }
}