leetcode----82. Remove Duplicates from Sorted List II

链接:

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

大意:

给定一个有序链表的头节点head,链表中含值相同的节点。要求去除链表中所有值相同的节点,只留下链表中值唯一的那些节点。例子:

思路:

由于是一个有序链表,所以判断一个节点的值是否重复,可以将当前节点的值与左右两边节点(如果不为null的话)的值进行比较。如果既不等于左节点的值也不等于右节点的值,那么该节点的值就是唯一的,将该节点添加到新链表即可。

代码:

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode h = new ListNode(0), pre = null, cur = head, newHead = h;
        while (cur != null) {
            ListNode next = cur.next;
            // 判断该节点的值是否重复 只需要判断其值和左右两节点的值是否相同即可
            if ((pre == null || cur.val != pre.val) && (next == null || cur.val != next.val)) {
                h.next = cur;
                h = h.next;
            }
            pre = cur;
            cur = next;
            h.next = null;
        }
        return newHead.next;
    }
}

结果:

结论:

提交之前,我还是感觉效率应该还可以的。可是....  有待优化 

其它:

又想着改了下,发现还都是1ms(弱...

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode h = new ListNode(0), dtj = head, cur = head.next, newHead = h; // dtj为待添加到新链表的节点 cur为当前遍历到的节点
        int count = 1;
        while (cur != null) {
            if (dtj.val == cur.val) {
                count++;
            } else {
                if (count == 1) {
                    h.next = dtj;
                    h = h.next;
                    h.next = null;
                }
                dtj = cur;
                count = 1;
            }
            cur = cur.next;
        }
        if (count == 1)
            h.next = dtj;
        return newHead.next;
    }
}
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode preOld = null, preNew = null, curNew = head, curOld = head;
        while (curOld != null) {
            ListNode next = curOld.next;
            // 判断该节点的值是否重复 只需要判断其值和左右两节点的值是否相同即可
            if ((preOld == null || curOld.val != preOld.val) && (next == null || curOld.val != next.val)) { // 唯一值
                curNew.val = curOld.val;
                preNew = curNew;
                curNew = curNew.next;
            }
            preOld = curOld;
            curOld = curOld.next;
        }
        if (preNew != null)
            preNew.next = null;
        else 
            return null;
        return head;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值