-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
68 lines (64 loc) · 1.55 KB
/
Solution.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* 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 ListNode modifiedList(int[] nums, ListNode head) {
HashSet<Integer> numSet = new HashSet<>();
for (int n : nums) {
numSet.add(n);
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null) {
if (numSet.contains(current.next.val)) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return dummy.next;
}
}
/*
* TIME LIMIT EXCEEDED
* MAY BE DUE TO NESTED LOOP : The isInNum method iterates through the nums
* array for each node in the linked list. This results in a time complexity of
* O(n * m), where:
* n is the number of nodes in the linked list.
* m is the length of the nums array.
* class Solution {
* public ListNode modifiedList(int[] nums, ListNode head) {
*
*
*
* ListNode dummy=new ListNode(0);
* dummy.next=head;
* ListNode current=dummy;
* while(current.next!=null){
* if(isInNum(current.next.val,nums)){
* current.next=current.next.next;
* }else{
* current=current.next;
* }
* }
*
* return dummy.next;
*
* }
* public boolean isInNum(int val, int[]nums){
* for(int n:nums){
* if(val==n){
* return true;
* } }
* return false;
* }
* }
*/