Post

[LeetCode 83] Remove Duplicates from Sorted List

LeetCode 83 (Java)
[Remove Duplicates from Sorted List] 문제 풀이

[LeetCode 83] Remove Duplicates from Sorted List

문제 바로가기


Description


Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.


Example 1


  • Input: head = [1,1,2]
  • Output: [1,2]


Example 2


  • Input: head = [1,1,2,3,3]
  • Output: [1,2,3]


Constraints


  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * 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 deleteDuplicates(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}


RuntimeMemory
0 ms44.4 MB


다른 풀이


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
class Solution {
    public ListNode deleteDuplicates(ListNode head) {

        ListNode current = head;

        while (current != null) {

            ListNode runner = current;

            while (runner.next != null) {

                if (runner.next.val == current.val) {
                    runner.next = runner.next.next; // remove duplicate
                } else {
                    runner = runner.next;
                }
            }

            current = current.next;
        }

        return head;
    }
}


Reference


  • https://github.com/doocs/leetcode/blob/main/solution/0000-0099/0083.Remove%20Duplicates%20from%20Sorted%20List/Solution.java
This post is licensed under CC BY 4.0 by the author.