Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How LeetCode removes repeating elements from a sorted list

Shulou Source: shulou.com Published: 2022-06-01 13:03:46 10月18日 Update

This article will explain in detail how to delete the repeated elements in the sorted list by LeetCode. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Brief introduction of the problem.

Given a sorted linked list, delete all nodes that contain duplicate numbers, leaving only those numbers that are not repeated in the original linked list.

2, example

Example 1:

Input: 1-> 2-> 3-> 3-> 4-> 4-> 5 output: 1-> 2-> 5 example 2:

Input: 1-> 1-> 1-> 2-> 3 output: 2-> 3

3, the train of thought of solving the problem

Use the Sentinel node to solve the set LinkedHashMap collection with key values.

4, problem solving procedure

Import java.util.*;import java.util.stream.Collectors

Public class DeleteDuplicatesTest3 {public static void main (String [] args) {ListNode L1 = new ListNode (1); ListNode L2 = new ListNode (2); ListNode L3 = new ListNode (3); ListNode L4 = new ListNode (3); ListNode L5 = new ListNode (4); ListNode L6 = new ListNode (4); ListNode L7 = new ListNode (5); l1.next = L2; l2.next = L3 L3.next = L4; l4.next = 15; l5.next = L6; l6.next = L7; ListNode listNode = deleteDuplicates (L1); System.out.println ("listNode =" + listNode);}

Public static ListNode deleteDuplicates (ListNode head) {if (head = = null) {return null;} if (head.next = = null) {return head;} HashMap hashMap = new LinkedHashMap (); ListNode dummyNode = head; while (dummyNode! = null) {hashMap.put (dummyNode.val, hashMap.getOrDefault (dummyNode.val, 0) + 1) DummyNode = dummyNode.next;} List list = hashMap.entrySet (). Stream (). Filter (Objects::nonNull) .filter (x-> x.getValue () = = 1) .map (Map.Entry::getKey) .filter (Collectors.toList ()); ListNode newHead = new ListNode (- 1); int size = list.size (); ListNode tempNode = newHead; for (int I = 0) I < size; iTunes +) {tempNode.next = new ListNode (list.get (I)); tempNode = tempNode.next;} return newHead.next;}

}

5. Picture version of the problem solving program.

On "LeetCode how to delete the repeated elements in the sorted list" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Tags: Sorting examples articles solutions elements numbers more programs nodes input output good original practical content Sentinels pictures ideas articles knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Shulou Technology macOS Docker