【LeetCode】Remove Duplicates from Sorted List
来源:互联网 发布:二维图形变换矩阵 编辑:程序博客网 时间:2024/06/06 17:16
题目
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
法1:从表头开始一个个比较下去,遇到相等的指向下一个;遇到不等的,更新要比较的节点,开始新一轮比较,代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head; } ListNode cur=head; while(cur.next!=null){ ListNode temp=cur.next; while(temp!=null&&cur.val==temp.val){ //只要相等就指向下一个节点 cur.next=temp.next; temp=temp.next; } if(cur.next!=null){ //注意判断cur是否是最后个元素 cur=cur.next; //取下一个元素开始下轮比较 } } return head; }}
法2:利用双指针的思想,一个指向当前不重复的最后一个元素,一个进行依次扫描,遇到不重复的则更新第一个指针,继续扫描,否则就把前面指针指向当前元素的下一个(即把当前元素从链表中删除)。时间上只需要一次扫描,所以是O(n),空间上两个额外指针,是O(1),代码如下:
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null){ return head; } ListNode pre=head; //要比较的节点 ListNode cur=head.next; while(cur!=null){ if(cur.val==pre.val){ pre.next=cur.next; }else{ pre=cur; //若不等,更新要比较的节点 } cur=cur.next; } return head; }}
---EOF---
0 0
- Remove Duplicates from Sorted List :from LeetCode
- Leetcode - List - Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- leetcode 37: Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List
- InputMethod窗口、wallpaper窗口管理关键函数分析
- ZigBee组网学习笔记(八)--温湿度传感器
- IM即时通讯实现原理
- firefox chrme 浏览器地址栏URL参数汉字BUG问题排查总结
- Java学习笔记之面向对象概念
- 【LeetCode】Remove Duplicates from Sorted List
- C 语言程序设计实践 3.13 矩阵坐标
- js控制文本框只输入数字和小数点
- 黑马程序员——OC语言核心语法
- Codeforces Round #277 (Div. 2)D题
- java并发编程(四)同步工具类
- Mac版Cornerstone破解方法
- cocos2d-x 2.2.0 控制lua脚本加载时的搜索路径
- 设计模式:单例模式