-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #538 from aishwarya-chandra/day9q3
day9q3
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
``` | ||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* int val; | ||
* ListNode next; | ||
* ListNode() {} | ||
* ListNode(int val) { this.val = val; } | ||
* ListNode(int val, ListNode next) { this.val = val; this.next = next; } | ||
* } | ||
*/ | ||
class Solution { | ||
public int numComponents(ListNode head, int[] nums) { | ||
HashSet<Integer> hs = new HashSet<>(); | ||
int count = 1; | ||
for(int i = 0; i < nums.length; i++) | ||
hs.add(nums[i]); | ||
boolean bool = true; | ||
boolean bool1 = true; | ||
while(head != null){ | ||
if(!hs.contains(head.val) && bool){ | ||
count++; | ||
bool = false; | ||
} | ||
else if(hs.contains(head.val)) | ||
bool = true; | ||
if(head.next == null && !hs.contains(head.val)) | ||
count--; | ||
if(bool1 && !hs.contains(head.val)) | ||
count--; | ||
bool1 = false; | ||
head = head.next; | ||
} | ||
return count; | ||
} | ||
} | ||
``` |