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

题目

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

示例1:

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

示例2:

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

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

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

解法

使用辅助set法

建立一个辅助的数据结构,用来保存节点值
搞一个虚拟头节点来遍历所有的节点

class Solution {
    
    
    public ListNode removeDuplicateNodes(ListNode head) {
    
    
        // 建立一个辅助的set用来判断使用有重复的节点值
        Set<Integer> set = new HashSet<>();
        // 建立虚拟头节点
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur = dummyHead;
        // 遍历节点 如果能够添加成功,说明没有重复的,继续向下遍历。否则说明有重复节点,跳过该节点
        while (cur.next != null) {
    
    
            if (set.add(cur.next.val)) {
    
    
                cur = cur.next;
            } else {
    
    
                cur.next = cur.next.next;
            }
        }
        return dummyHead.next;
    }
}

位运算法

使用位运算来判断是否有重复值

class Solution {
    
    
    public ListNode removeDuplicateNodes(ListNode head) {
    
    
        int[] bits = new int[20000 / 32 + 1];
        ListNode cur = head;
        while (cur != null && cur.next != null) {
    
    
            bits[cur.val / 32] |= 1 << (cur.val % 32);
            // 如果有重复值
            if ((bits[cur.next.val / 32] & (1 << (cur.next.val % 32))) != 0)
                cur.next = cur.next.next;
            else
                cur = cur.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_17677907/article/details/112943750