zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版

    题目:

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    原始思路:保存前一位的指针,这样在重复的时候,可以直接用next指向新的位置,需要注意的是开始时候,需要进行额外的判断是否有重复,才能形成错位的指针。

    原始代码:

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode req = head;
            ListNode pre = head;
            
            //判断初始是否有重复
            while(head != null){
                head = head.next;   // 直到没有重复,head位于pre的下一位
                if(head != null && pre.val == head.val){
                    do{
                        head = head.next;
                    }
                    while(head!=null && head.val == pre.val);
                    pre = head;
                    req = head;
                }else break;    
            }
            //过程中判断,pre始终在head前一位    
            while(head != null){
                head = head.next;
                if(head!=null && pre.next.val == head.val){
                    do{
                        head = head.next;
                    }
                    while(head!=null && head.val == pre.next.val);
                    pre.next = head;
                }
                else pre = pre.next;            
            }
            
            return req;
        }
    }

    修改思路:可以建立一个虚拟表头,next指向head,这样可以把原始代码中初始部分的额外判断优化掉,代码十分简洁。

    修改后代码:

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode dunmy = new ListNode(Integer.MIN_VALUE);
            dunmy.next = head;
            ListNode pre = dunmy;
    
            while(head != null){
                head = head.next;
                if(head!=null && pre.next.val == head.val){
                    do{
                        head = head.next;
                    }
                    while(head!=null && head.val == pre.next.val);
                    pre.next = head;
                }
                else pre = pre.next;            
            }
            
            return dunmy.next;
        }
    }
  • 相关阅读:
    谷歌关闭中国区购物搜索小思考
    java生成本地头文件用javah出错问题
    hadoop源代码分析(4)org.apache.hadoop.util包GenericOptionsParser类【原创】
    Ext.util.MixedCollection 用法
    eval 函数用法
    Rails Devise_demo
    rails rake 指南
    accepts_nested_attributes_for
    将Rails3.0无缝升级到Rails3.1.0.beta1
    spork + autotest 实现rails自动化测试
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4512239.html
Copyright © 2011-2022 走看看