likes
comments
collection
share

Java&C++题解与拓展——leetcode817.链表组件【么的新知识】

作者站长头像
站长
· 阅读数 15
每日一题做题记录,参考官方和三叶的题解

题目要求

Java&C++题解与拓展——leetcode817.链表组件【么的新知识】

Java&C++题解与拓展——leetcode817.链表组件【么的新知识】

思路:模拟

Java

class Solution {
    public int numComponents(ListNode head, int[] nums) {
        int res = 0;
        Set<Integer> set = new HashSet<>();
        for (int x : nums)
            set.add(x); // 转存nums
        while (head != null) {
            if (set.contains(head.val)) {
                while (head != null && set.contains(head.val))
                    head = head.next;
                res++;
            }
            else {
                head = head.next;
            }
        }
        return res;
    }
}
  • 时间复杂度:O(n)O(n)O(n),遍历整个链表
  • 空间复杂度:O(n)O(n)O(n),转存numsnumsnums

C++

class Solution {
public:
    int numComponents(ListNode* head, vector<int>& nums) {
        int res = 0;
        unordered_set<int> set(nums.begin(), nums.end()); // 转存nums
        while (head) {
            if (set.count(head->val)) {
                while (head && set.count(head->val))
                    head = head->next;
                res++;
            }
            else {
                head = head->next;
            }
        }
        return res;
    }
};
  • 时间复杂度:O(n)O(n)O(n),遍历整个链表
  • 空间复杂度:O(n)O(n)O(n),转存numsnumsnums

Rust

use std::collections::HashSet;
impl Solution {
    pub fn num_components(mut head: Option<Box<ListNode>>, nums: Vec<i32>) -> i32 {
        let mut head = head.as_ref();
        let mut res = 0;
        let mut status = false; // 是否处于同一个组件
        while let Some(node) = head {
            if nums.contains(&node.val) {
                if !status {
                    res += 1;
                    status = true;
                }
            } else {
                status = false;
            }
            head = node.next.as_ref();
        }
        res
    }
}
  • 时间复杂度:O(n)O(n)O(n),遍历整个链表
  • 空间复杂度:O(n)O(n)O(n),转存numsnumsnums

总结

简单模拟题,没想到转存用哈希表的内置函数,还想着要排序方便查找……对于消耗空间的方法总是不太敏感。

欢迎指正与讨论!