【leetcode】面试题 02.01. 移除重复节点

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例1:

输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:

输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:

链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
进阶:

如果不得使用临时缓冲区,该怎么解决?

题解:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        HashSet<Integer> set = new HashSet<>();
        ListNode newhead = new ListNode(-1);
        ListNode p = newhead;
        while(null != head) {
            if(!set.contains(head.val)){
                p.next = head;
                p = p.next;
                set.add(head.val);
                head = head.next;
            }else{
                p.next = head.next;
                head = head.next;
            }
        }
        return newhead.next;
    }
}

如果不用缓冲区,需要用时间换空间,那么题解为:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode pre = head;
        ListNode next;
        ListNode p;
        while(pre != null ) {
            p = pre;
            next = p.next;
            while(next != null){
                // 如果和上层循环相同的话,删除next指向的节点
                if(next.val == pre.val){
                    p.next = next.next;
                    next = next.next;
                }else{
                    p = p.next;
                    next =next.next;
                }
            }
            pre = pre.next;
        }
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值