目录 题目要求 思路:模拟 Java C++ Rust 总结 题目要求 思路:模拟 Java class Solution { public int numComponents(ListNode head, int[] nums) { int res = 0; SetInteger set = new HashSet(); for (int x : nums) set.add(x); //
目录
- 题目要求
- 思路:模拟
- Java
- C++
- Rust
- 总结
题目要求
思路:模拟
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),转存nums
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),转存nums
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),转存nums
总结
简单模拟题,没想到转存用哈希表的内置函数,还想着要排序方便查找……对于消耗空间的方法总是不太敏感。
以上就是Java C++题解leetcode817链表组件示例的详细内容,更多关于Java C++题解链表组件的资料请关注自由互联其它相关文章!