LeetCode-Remove Duplicates from Sorted List II
来源:互联网 发布:java 浏览器 编辑:程序博客网 时间:2024/05/23 13:48
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24017313
时间:2014-4-18
题目
Remove Duplicates from Sorted List II
Total Accepted: 9519 Total Submissions: 38686My SubmissionsGiven 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
.
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
解法
几个不同想法:
- 用循环列表来删除
- 先扫描一遍记住要删除的元素,然后再扫一遍删除
解释:这两个方法前一个行不通,因为不是去重而是删去重复的所有数字,故基于频率的循环删除不可以。后者太麻烦,虽然可能只用一个指针解决问题,但是要多一次循环并且需要更多的空间。
/** * 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 p = head; ListNode dummy = new ListNode(Integer.MIN_VALUE); ListNode pre = dummy; int del = Integer.MIN_VALUE; while(p!=null&&p.next!=null){ if(p.val == p.next.val){ del = p.val; while(p.val == del){ p=p.next; if(p==null) return dummy.next; } } else{ pre.next = p; pre = pre.next; p=p.next; pre.next = null; } } pre.next = p; return dummy.next; }}
返回
LeetCode Solution(持续更新,java>c++)
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- 递增数列中找和为s乘积最小的两个数
- RedHat 6.4 64位 图文安装Oracle 11g
- C++中的const限定修饰符
- 【Halcon】halcon中的常用算子的中文说明
- 你会购买电子书吗
- LeetCode-Remove Duplicates from Sorted List II
- 梯度下降算法- gradient descent
- C++中获取WinNT/Win2k当前用户名和密码
- 阶梯博弈(poj 1704)
- CWnd::NotifyWinEvent 函数不接受 4 个参数的解决方案
- C++中确定基类有虚析构函数
- VC 删除指定目录(文件夹)-RemoveDirectory使用
- 自己写的列出盘符下的所有文件树
- Linux -- 内存控制之oom killer机制及代码分析