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); // 轉(zhuǎn)存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;
}
}
- 時(shí)間復(fù)雜度:O(n),遍歷整個(gè)鏈表
- 空間復(fù)雜度:O(n),轉(zhuǎn)存nums
C++
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums) {
int res = 0;
unordered_set<int> set(nums.begin(), nums.end()); // 轉(zhuǎn)存nums
while (head) {
if (set.count(head->val)) {
while (head && set.count(head->val))
head = head->next;
res++;
}
else {
head = head->next;
}
}
return res;
}
};
- 時(shí)間復(fù)雜度:O(n),遍歷整個(gè)鏈表
- 空間復(fù)雜度:O(n),轉(zhuǎ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; // 是否處于同一個(gè)組件
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
}
}
- 時(shí)間復(fù)雜度:O(n),遍歷整個(gè)鏈表
- 空間復(fù)雜度:O(n),轉(zhuǎn)存nums
總結(jié)
簡(jiǎn)單模擬題,沒(méi)想到轉(zhuǎn)存用哈希表的內(nèi)置函數(shù),還想著要排序方便查找……對(duì)于消耗空間的方法總是不太敏感。
以上就是Java C++題解leetcode817鏈表組件示例的詳細(xì)內(nèi)容,更多關(guān)于Java C++題解鏈表組件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java Spring Controller 獲取請(qǐng)求參數(shù)的幾種方法詳解
這篇文章主要介紹了Java Spring Controller 獲取請(qǐng)求參數(shù)的幾種方法詳解的相關(guān)資料,這里提供了6種方法,需要的朋友可以參考下2016-12-12
Spring中的@EnableConfigurationProperties使用方式以及作用詳解
這篇文章主要介紹了Spring中的@EnableConfigurationProperties使用方式以及作用詳解,使用了?@ConfigurationProperties?注解的配置類生效,將該類注入到?IOC?容器中,交由?IOC?容器進(jìn)行管理,此時(shí)則不用再配置類上加上@Component,需要的朋友可以參考下2024-01-01
Spring Boot項(xiàng)目中如何對(duì)接口請(qǐng)求參數(shù)打印日志
在SpringBoot項(xiàng)目中,打印接口請(qǐng)求參數(shù)有多種方法,如使用AOP、控制器建議、攔截器、@ModelAttribute、SpringBootActuator、日志框架的MDC、自定義過(guò)濾器和SpringWebflux,這些方法有助于API調(diào)試和監(jiān)控,但需注意隱私和敏感信息安全2024-10-10
Java網(wǎng)絡(luò)編程之IO模型阻塞與非阻塞簡(jiǎn)要分析
這篇文章主要介紹Java網(wǎng)絡(luò)編程中的IO模型阻塞與非阻塞簡(jiǎn)要分析,文中附有示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09

