目录
- 题目要求
- 思路:模拟
- 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++题解链表组件的资料请关注其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)