반응형
Recent Posts
Notice
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- DP
- 부분배열
- HashMap
- 깊이우선탐색
- greedy
- coding
- priority queue
- 브루트포스
- ArrayList
- programmers
- 우선순위 큐
- string
- hashset
- binary tree
- 리트코드
- PCCP
- Array
- leetcode
- Java
- Algorithm
- 알고리즘
- recursion
- 재귀함수
- dfs
- two pointers
Archives
- Today
- Total
지식창고
[Java]LeetCode 817. Linked List Components 본문
728x90
반응형
LeetCode 817. Linked List Components - Java
문제 :
Linked List를 주고 그 Linked List의 subset을 준다.
주어진 Linked List를 기준으로 subset List가 순서대로 이어진 그룹이 몇 개인지 센다.
Input: head = [0,1,2,3], nums = [0,1,3]
Output: 2
Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
[0, 1] , [3] -> 2
HashSet 생성
HashSet의 특징 : 중복을 허용하지 않는다.
Set<Integer> set = new HashSet<>();
nums를 HashSet에 추가한다.
for(int i: nums){
set.add(i);
}
Component의 연결이 마지막이라는 것을 알 수 있는 조건
1 .head 노드의 마지막인 경우
2. 현재 노드 기준 다음 노드의 값이 nums에 포함되지 않았을 경우
Component의 연결이 유지될 수 있는 조건
1. 현재 노드의 값이 HashSet에 포함되어 있는 경우
head를 처음부터 검사하면서 위 두 조건을 적용해 노드들을 그룹핑해주며 result 값을 더해준다.
while(head != null){
if(set.contains(head.val) && (head.next == null || !(set.contains(head.next.val)) ) ){
result++;
}
head = head.next;
}
결 과
class Solution {
public int numComponents(ListNode head, int[] nums) {
Set<Integer> set = new HashSet<>();
int result =0;
for(int i: nums){
set.add(i);
}
while(head != null){
if(set.contains(head.val) && (head.next == null || !(set.contains(head.next.val)) ) ){
result++;
}
head = head.next;
}
return result;
}
}
728x90
반응형
'Algorithm > Leetcode' 카테고리의 다른 글
[Java] LeetCode 452. Minimum Number of Arrows to Burst Balloons (0) | 2023.01.06 |
---|---|
[Java]LeetCode 2244. Minimum Rounds to Complete All Tasks (2) | 2023.01.04 |
[Java]LeetCode 1834. Single-Threaded CPU (0) | 2022.12.29 |
[Java]LeetCode 1962. Remove Stones to Minimize the Total (0) | 2022.12.28 |
[Java]LeetCode 791. Custom Sort String (0) | 2022.12.24 |
Comments