You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* The sum of `lists[i].length` won't exceed `10^4`.
37
-
38
-
To solve the "Merge k Sorted Lists" problem in Java with a `Solution` class, we can use a priority queue (min-heap) to efficiently merge the lists. Here are the steps:
39
-
40
-
1. Define a `Solution` class.
41
-
2. Define a method named `mergeKLists` that takes an array of linked lists `lists` as input and returns a single sorted linked list.
42
-
3. Create a priority queue of ListNode objects. We will use this priority queue to store the heads of each linked list.
43
-
4. Iterate through each linked list in the input array `lists` and add the head node of each list to the priority queue.
44
-
5. Create a dummy ListNode object to serve as the head of the merged sorted linked list.
45
-
6. Initialize a ListNode object named `current` to point to the dummy node.
46
-
7. While the priority queue is not empty:
47
-
- Remove the ListNode with the smallest value from the priority queue.
48
-
- Add this node to the merged linked list by setting the `next` pointer of the `current` node to this node.
49
-
- Move the `current` pointer to the next node in the merged linked list.
50
-
- If the removed node has a `next` pointer, add the next node from the same list to the priority queue.
51
-
8. Return the `next` pointer of the dummy node, which points to the head of the merged sorted linked list.
52
-
53
-
Here's the implementation:
54
-
55
-
```java
56
-
importjava.util.PriorityQueue;
57
-
58
-
publicclassSolution {
59
-
publicListNodemergeKLists(ListNode[] lists) {
60
-
PriorityQueue<ListNode> minHeap =newPriorityQueue<>((a, b) -> a.val - b.val);
61
-
62
-
// Add the heads of all lists to the priority queue
63
-
for (ListNode node : lists) {
64
-
if (node !=null) {
65
-
minHeap.offer(node);
66
-
}
67
-
}
68
-
69
-
// Create a dummy node to serve as the head of the merged list
70
-
ListNode dummy =newListNode(0);
71
-
ListNode current = dummy;
72
-
73
-
// Merge the lists
74
-
while (!minHeap.isEmpty()) {
75
-
ListNode minNode = minHeap.poll();
76
-
current.next = minNode;
77
-
current = current.next;
78
-
79
-
if (minNode.next !=null) {
80
-
minHeap.offer(minNode.next);
81
-
}
82
-
}
83
-
84
-
return dummy.next;
85
-
}
86
-
87
-
publicstaticvoidmain(String[] args) {
88
-
Solution solution =newSolution();
89
-
90
-
// Test case
91
-
ListNode[] lists =newListNode[] {
92
-
ListNode.createList(newint[] {1, 4, 5}),
93
-
ListNode.createList(newint[] {1, 3, 4}),
94
-
ListNode.createList(newint[] {2, 6})
95
-
};
96
-
System.out.println("Merged list:");
97
-
ListNode.printList(solution.mergeKLists(lists));
98
-
}
99
-
}
100
-
101
-
classListNode {
102
-
int val;
103
-
ListNode next;
104
-
105
-
ListNode(intval) {
106
-
this.val = val;
107
-
}
108
-
109
-
staticListNodecreateList(int[] arr) {
110
-
if (arr ==null|| arr.length ==0) {
111
-
returnnull;
112
-
}
113
-
114
-
ListNode dummy =newListNode(0);
115
-
ListNode current = dummy;
116
-
for (int num : arr) {
117
-
current.next =newListNode(num);
118
-
current = current.next;
119
-
}
120
-
return dummy.next;
121
-
}
122
-
123
-
staticvoidprintList(ListNodehead) {
124
-
while (head !=null) {
125
-
System.out.print(head.val +"");
126
-
head = head.next;
127
-
}
128
-
System.out.println();
129
-
}
130
-
}
131
-
```
132
-
133
-
This implementation provides a solution to the "Merge k Sorted Lists" problem in Java using a priority queue.
36
+
* The sum of `lists[i].length` will not exceed <code>10<sup>4</sup></code>.
* The number of nodes in the list is in the range `[0, 100]`.
30
-
*`0 <= Node.val <= 100`
31
-
32
-
To solve the "Swap Nodes in Pairs" problem in Java with a `Solution` class, we can traverse the linked list while swapping pairs of nodes. Here are the steps:
33
-
34
-
1. Define a `Solution` class.
35
-
2. Define a method named `swapPairs` that takes the head of a linked list as input and returns the head of the modified list.
36
-
3. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list.
37
-
4. Initialize three pointers: `prev`, `first`, and `second`.
38
-
5. Iterate through the list while `first` and `second` are not null:
39
-
- Assign `first` to the `next` pointer of `prev`.
40
-
- Assign `second` to the `next` pointer of `first`.
41
-
- Assign the `next` pointer of `prev` to the `next` pointer of `second`.
42
-
- Assign the `next` pointer of `second` to `first`.
43
-
- Move `prev` to `first`.
44
-
- Move `first` to `first.next` (which is the next pair of nodes).
45
-
6. Return the `next` pointer of the dummy node, which points to the head of the modified list.
46
-
47
-
Here's the implementation:
48
-
49
-
```java
50
-
publicclassSolution {
51
-
publicListNodeswapPairs(ListNodehead) {
52
-
// Create a dummy node and point its next to the head
53
-
ListNode dummy =newListNode(0);
54
-
dummy.next = head;
55
-
56
-
// Initialize pointers
57
-
ListNode prev = dummy;
58
-
ListNode first, second;
59
-
60
-
// Swap pairs of nodes
61
-
while (prev.next !=null&& prev.next.next !=null) {
62
-
first = prev.next;
63
-
second = first.next;
64
-
65
-
// Swap nodes
66
-
prev.next = second;
67
-
first.next = second.next;
68
-
second.next = first;
69
-
70
-
// Move prev to the next pair of nodes
71
-
prev = first;
72
-
}
73
-
74
-
return dummy.next;
75
-
}
76
-
}
77
-
```
78
-
79
-
This implementation provides a solution to the "Swap Nodes in Pairs" problem in Java without modifying the values in the list's nodes.
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md
+5-84Lines changed: 5 additions & 84 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,9 +2,9 @@
2
2
3
3
Hard
4
4
5
-
Given a linked list, reverse the nodes of a linked list _k_ at a time and return its modified list.
5
+
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
6
6
7
-
_k_ is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of _k_ then left-out nodes, in the end, should remain as it is.
7
+
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.
8
8
9
9
You may not alter the values in the list's nodes, only nodes themselves may be changed.
10
10
@@ -24,89 +24,10 @@ You may not alter the values in the list's nodes, only nodes themselves may be c
24
24
25
25
**Output:**[3,2,1,4,5]
26
26
27
-
**Example 3:**
28
-
29
-
**Input:** head = [1,2,3,4,5], k = 1
30
-
31
-
**Output:**[1,2,3,4,5]
32
-
33
-
**Example 4:**
34
-
35
-
**Input:** head = [1], k = 1
36
-
37
-
**Output:**[1]
38
-
39
27
**Constraints:**
40
28
41
-
* The number of nodes in the list is in the range `sz`.
42
-
*`1 <= sz <= 5000`
29
+
* The number of nodes in the list is `n`.
30
+
*`1 <= k <= n <= 5000`
43
31
*`0 <= Node.val <= 1000`
44
-
*`1 <= k <= sz`
45
-
46
-
**Follow-up:** Can you solve the problem in O(1) extra memory space?
47
-
48
-
To solve the "Reverse Nodes in k-Group" problem in Java with a `Solution` class, we can reverse the nodes in groups of k using a recursive approach. Here are the steps:
49
-
50
-
1. Define a `Solution` class.
51
-
2. Define a method named `reverseKGroup` that takes the head of a linked list and an integer k as input and returns the head of the modified list.
52
-
3. Define a helper method named `reverse` that takes the head and tail of a sublist as input and reverses the sublist in place. This method returns the new head of the sublist.
53
-
4. Create a dummy ListNode object and set its `next` pointer to the head of the input list. This dummy node will serve as the new head of the modified list.
54
-
5. Initialize pointers `prev`, `curr`, `next`, and `tail`. Set `prev` and `tail` to the dummy node, and `curr` to the head of the input list.
55
-
6. Iterate through the list:
56
-
- Move `curr` k steps forward. If it's not possible (i.e., there are less than k nodes left), break the loop.
57
-
- Set `next` to the `next` pointer of `curr`.
58
-
- Reverse the sublist from `curr` to `next` using the `reverse` method. Update `prev` and `tail` accordingly.
59
-
- Move `prev` and `tail` k steps forward to the last node of the reversed sublist.
60
-
- Move `curr` to `next`.
61
-
7. Return the `next` pointer of the dummy node, which points to the head of the modified list.
62
-
63
-
Here's the implementation:
64
-
65
-
```java
66
-
publicclassSolution {
67
-
publicListNodereverseKGroup(ListNodehead, intk) {
68
-
// Create a dummy node and point its next to the head
69
-
ListNode dummy =newListNode(0);
70
-
dummy.next = head;
71
-
72
-
// Initialize pointers
73
-
ListNode prev = dummy, curr = head, next, tail;
74
-
75
-
// Iterate through the list and reverse in groups of k
76
-
while (true) {
77
-
// Move curr k steps forward
78
-
tail = prev;
79
-
for (int i =0; i < k; i++) {
80
-
tail = tail.next;
81
-
if (tail ==null) return dummy.next; // Less than k nodes left
82
-
}
83
-
84
-
next = tail.next; // Save the next pointer of the sublist
85
-
tail.next =null; // Disconnect the sublist from the rest of the list
86
-
87
-
// Reverse the sublist and update prev and tail pointers
88
-
prev.next = reverse(curr, tail);
89
-
tail.next = next; // Connect the reversed sublist back to the rest of the list
90
-
91
-
// Move prev, tail, and curr to the next group
92
-
prev = curr;
93
-
curr = next;
94
-
}
95
-
}
96
-
97
-
// Helper method to reverse a sublist from head to tail
return prev; // Return the new head of the reversed sublist
108
-
}
109
-
}
110
-
```
111
32
112
-
This implementation provides a solution to the "Reverse Nodes in k-Group" problem in Java without modifying the values in the list's nodes. It recursively reverses the nodes in groups of k.
33
+
**Follow-up:** Can you solve the problem in `O(1)` extra memory space?
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0026_remove_duplicates_from_sorted_array/readme.md
+4-14Lines changed: 4 additions & 14 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,25 +4,15 @@ Easy
4
4
5
5
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**.
6
6
7
-
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
7
+
Consider the number of _unique elements_ in `nums` to be `k`. After removing duplicates, return the number of unique elements `k`.
8
8
9
-
Return `k`_after placing the final result in the first_`k`_slots of_`nums`.
10
-
11
-
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
9
+
The first `k` elements of `nums` should contain the unique numbers in **sorted order**. The remaining elements beyond index `k - 1` can be ignored.
12
10
13
11
**Custom Judge:**
14
12
15
13
The judge will test your solution with the following code:
16
14
17
-
int[] nums = [...]; // Input array
18
-
int[] expectedNums = [...]; // The expected answer with correct length
19
-
20
-
int k = removeDuplicates(nums); // Calls your implementation
21
-
22
-
assert k == expectedNums.length;
23
-
for (int i = 0; i < k; i++) {
24
-
assert nums[i] == expectedNums[i];
25
-
}
15
+
int[] nums = [...]; // Input array int[] expectedNums = [...]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; }
26
16
27
17
If all assertions pass, then your solution will be **accepted**.
28
18
@@ -44,6 +34,6 @@ If all assertions pass, then your solution will be **accepted**.
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0027_remove_element/readme.md
+5-17Lines changed: 5 additions & 17 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,30 +2,18 @@
2
2
3
3
Easy
4
4
5
-
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums`[**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The relative order of the elements may be changed.
5
+
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums`[**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_`nums`_which are not equal to_`val`.
6
6
7
-
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
7
+
Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:
8
8
9
-
Return `k`_after placing the final result in the first_`k`_slots of_`nums`.
10
-
11
-
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
9
+
* Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
10
+
* Return `k`.
12
11
13
12
**Custom Judge:**
14
13
15
14
The judge will test your solution with the following code:
16
15
17
-
int[] nums = [...]; // Input array
18
-
int val = ...; // Value to remove
19
-
int[] expectedNums = [...]; // The expected answer with correct length.
20
-
// It is sorted with no values equaling val.
21
-
22
-
int k = removeElement(nums, val); // Calls your implementation
23
-
24
-
assert k == expectedNums.length;
25
-
sort(nums, 0, k); // Sort the first k elements of nums
26
-
for (int i = 0; i < actualLength; i++) {
27
-
assert nums[i] == expectedNums[i];
28
-
}
16
+
int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; }
29
17
30
18
If all assertions pass, then your solution will be **accepted**.
0 commit comments