[LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1513字,纯文字阅读大概需要3分钟。
内容图文
![[LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版](/upload/InfoBanner/zyjiaocheng/1185/c5405f8dd17e417e8ef79e2d246f1e31.jpg)
题目:
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; }elsebreak; } //过程中判断,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; } }
原文:http://www.cnblogs.com/TinyBobo/p/4512239.html
内容总结
以上是互联网集市为您收集整理的[LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版全部内容,希望文章能够帮你解决[LeetCode-JAVA] Remove Duplicates from Sorted List II 优化版所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。