美文网首页
面试题 02.01. 移除重复节点

面试题 02.01. 移除重复节点

作者: 编程小王子AAA | 来源:发表于2020-07-28 21:42 被阅读0次

出自程序员的面试金典#### 面试题 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; }
 * }
 */
方法一:用set
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head==null || head.next==null) return head;
        HashSet<Integer> set=new HashSet<>();
        set.add(head.val);
        ListNode pre=head;
        ListNode cur=head.next;
        while(cur!=null){
            if(set.contains(cur.val)){
                pre.next=cur.next;
            }else{
                set.add(cur.val);
                pre=cur;
            }
            cur=cur.next;
        }
        return head;
    }
}

方法二:时间复杂度为n*n
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;
    }
}

相关文章

网友评论

      本文标题:面试题 02.01. 移除重复节点

      本文链接:https://www.haomeiwen.com/subject/mxgqrktx.html