leetcode每日一题(2020-06-26):面试题 02.01. 移除重复节点

题目描述:
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
进阶要求:如果不得使用临时缓冲区,该怎么解决?

今日学习:
1.链表和数组的相互转换
2.巩固链表概念

题解:
1.我的想法:链表存进Set去重,Set转成数组再转成链表
2.利用Set不重复特性,遍历链表,Set中有val就跳过节点拼接,没有val就存进set
3.不用缓存:双指针遍历链表

// 1.Set+转换
var removeDuplicateNodes = function(head) {
    // 1.将head中的值存进set去重
    if(!head) return head
    let h = new Set()
    let pre = head
    while(pre) {
        h.add(pre.val)
        pre = pre.next
    }
    // 2.set转成array再转成新链表输出
    let arr = Array.from(h)
    let res = new ListNode(arr[0])
    let prev = res
    for(let i = 1; i < arr.length; i++) {
        prev.next = new ListNode(arr[i])
        prev = prev.next
    }
    return res
};
// 2.Set缓存
var removeDuplicateNodes = function(head) {
    let h = new Set() //用来判断是否重复
    let temp = new ListNode(0)
    temp.next = head
    while(temp.next) {
        if(!h.has(temp.next.val)) {
            h.add(temp.next.val)
            temp = temp.next
        } else {
            temp.next = temp.next.next
        }
    }
    return head
}
// 3.双指针不用缓存
var removeDuplicateNodes = function(head) {
    let p = head
    while(p) {
        q = p
        while(q.next) {
            if(q.next.val == p.val) {
                q.next = q.next.next
            }else {
                q = q.next
            }
        }
        p = p.next
    }
    return head
}

猜你喜欢

转载自www.cnblogs.com/autumn-starrysky/p/13194498.html