【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]范围内。

进阶:

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


思路一:

使用哈希表结构,由于要删除一个节点
所以必须有两个指针最好,容易记住

如果没有被添加,则指针右移 pos=pos.next;
如果被添加了,则断掉其连接的边即可 pos.next=pos.next.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){
            return head;
        }
        Set<Integer>set =new HashSet<>();
        set.add(head.val);

        ListNode pos=head;
        while(pos.next!=null){
            ListNode cur =pos.next;
            if(set.add(cur.val)){
               pos=pos.next;
                
            }else{
                pos.next=pos.next.next;
                
            }

        }
        return head;
    }
}

如果只使用一个指针
具体如下

/**
 * 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){
            return head;
        }
        Set<Integer>set =new HashSet<>();
        set.add(head.val);

        ListNode pos=head;
        while(pos.next!=null){
            if(set.add(pos.next.val)){
               pos=pos.next;
                
            }else{
                pos.next=pos.next.next;
                
            }

        }
        return head;
    }
}

思路二:

不能用空间
那就换时间
但是复杂度有点高,不建议

class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        ListNode ob = head;
        while (ob != null) {
            ListNode oc = ob;
            while (oc.next != null) {
                if (oc.next.val == ob.val) {
                    oc.next = oc.next.next;
                } else {
                    oc = oc.next;
                }
            }
            ob = ob.next;
        }
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值