题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        ListNode cur = head;
        while (cur != null) {
            int cnt = 0;
            int tmp = cur.val;
            ListNode pre = cur;
            while (cur != null && cur.val == tmp) {
                cnt++;
                cur = cur.next;
            }
            if (cnt == 1) {
                tail.next = pre;
                tail = pre;
            }
        }
        tail.next = null;
        return dummy.next;
    }

    public ListNode deleteDuplicates2 (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        Map<Integer, Integer> map = new HashMap<>();
        ListNode cur = head;
        while (cur != null) {
            map.put(cur.val, map.getOrDefault(cur.val, 0) + 1);
            cur = cur.next;
        }
        ListNode dummy = new ListNode(-1);
        ListNode tail = dummy;
        cur = head;
        while (cur != null) {
            if (map.get(cur.val) == 1) {
                tail.next = cur;
                tail = cur;
            }
            cur = cur.next;
        }
        tail.next = null;
        return dummy.next;
    }
}

全部评论

相关推荐

迟缓的斜杠青年巴比Q了:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
06-25 21:00
门头沟学院 Java
多拆解背记一下当前的高频场景面试题,结合自己的项目经历去作答,面试通过率原来真的不会低!
牛客965593684号:小公司不就是这样的吗,面试要么是点击就送,要么就是往死里拷打,没有一个统一的标准。这个不能代表所有公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务