这篇文章主要为大家介绍了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),转存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++题解链表组件的资料请关注编程学习网其它相关文章!
沃梦达教程
本文标题为:Java C++题解leetcode817链表组件示例
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
猜你喜欢
- Java中的日期时间处理及格式化处理 2023-04-18
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Java实现顺序表的操作详解 2023-05-19
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- JSP页面间传值问题实例简析 2023-08-03
- JSP 制作验证码的实例详解 2023-07-30
- 深入了解Spring的事务传播机制 2023-06-02