目录题目要求思路:模拟Javac++Rust总结题目要求 思路:模拟 Java class Solution { public int numComponents(List
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;
}
}
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;
}
};
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
}
}
简单模拟题,没想到转存用哈希表的内置函数,还想着要排序方便查找……对于消耗空间的方法总是不太敏感。
以上就是Java C++题解LeetCode817链表组件示例的详细内容,更多关于Java C++题解链表组件的资料请关注编程网其它相关文章!
--结束END--
本文标题: Java C++题解leetcode817链表组件示例
本文链接: https://lsjlt.com/news/169264.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0