[LeetCode] 1836. Remove Duplicates From an Unsorted Linked List


Given the head of a linked list, find all the values that appear more than once in the list and delete the nodes that have any of those values.

Return the linked list after the deletions.

Example 1:

Input: head = [1,2,3,2]
Output: [1,3]
Explanation: 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with [1,3].

Example 2:

Input: head = [2,1,1,2]
Output: []
Explanation: 2 and 1 both appear twice. All the elements should be deleted.

Example 3:

Input: head = [3,2,2,1,3,2,4]
Output: [1,4]
Explanation: 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with [1,4].

Constraints:

  • The number of nodes in the list is in the range [1, 105]
  • 1 <= Node.val <= 105

從一個未排序的鏈表中移除重復的節點。

題意是給一個單鏈表,鏈表中的 node.val 是亂序的,請你找到那些 val 出現次數超過一次的 node 並將他們刪去,返回刪除后的鏈表。

思路是需要掃描兩遍,這里我們同時需要一個 hashmap 記錄每個不同 node.val 的出現次數。第一遍掃描的時候記錄每個不同 node.val 的出現次數,第二遍掃描的時候,需要創建一個新的 dummy 節點,用dummy.next去試探下一個節點是否是需要刪除的節點,如果是,就直接跳過即可。

時間O(n)

空間O(n)

Java實現

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode deleteDuplicatesUnsorted(ListNode head) {
13         // HashMap<Integer, Integer> map = new HashMap<>();
14         int[] map = new int[(int) Math.pow(10, 5) + 1];
15         // dummy - 最后需要return用的
16         // dummy2 - 第二遍掃描的時候需要用的,因為涉及到刪除操作,所以只能用.next試探
17         ListNode dummy = new ListNode(0);
18         ListNode dummy2 = dummy;
19         dummy.next = head;
20 
21         ListNode cur = head;
22         while (cur != null) {
23             // map.put(cur.val, map.getOrDefault(cur.val, 0) + 1);
24             map[cur.val]++;
25             cur = cur.next;
26         }
27 
28         while (dummy2.next != null) {
29             // if (map.getOrDefault(dummy2.next.val, 0) > 1) {
30             if (map[dummy2.next.val] > 1) {
31                 dummy2.next = dummy2.next.next;
32             } else {
33                 dummy2 = dummy2.next;
34             }
35         }
36         return dummy.next;
37     }
38 }

 

相關題目

83. Remove Duplicates from Sorted List

82. Remove Duplicates from Sorted List II

1836. Remove Duplicates From an Unsorted Linked List

LeetCode 題目總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM