2.2.4 Remove Duplicates from Sorted List
来源:互联网 发布:浙江外商直接投资数据 编辑:程序博客网 时间:2024/05/17 03:04
Link: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
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 while cur.val == pre.val ,只更新cur;一旦不同,才更新pre.next = cur (遇到相同的都跳过,遇到不同的,才一次性把跳过的所有相同的都删掉)
2 没走一步,只要相同就删除: pre.next = cur.next
思路1:我开始的代码:
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode pre = head; ListNode cur = head; while(cur.next != null){ if(cur.next.val == pre.val){ cur = cur.next; } else{ cur = cur.next; pre.next = cur; pre = pre.next; } } return head; }}
修改后的代码:只加了一行
Time: O(n), Space: O(1)
pre.next = cur.next;
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode pre = head; ListNode cur = head; while(cur.next != null){ if(cur.next.val == pre.val){ cur = cur.next; } else{ cur = cur.next; pre.next = cur; pre = pre.next; } } pre.next = cur.next; return head; }}
这种思路有个问题:如果cur.val != pre.val, 我们还是设pre.next = cur (实际上pre.next的指针没变,这步是多余的操作)
正确答案2:while嵌套while
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return null; if(head.next == null) return head; ListNode pre = head; ListNode cur = head.next; while(cur != null){ while(cur != null && cur.val == pre.val){ cur = cur.next; } pre.next = cur; pre = cur; } return head; }}
思路2:http://blog.csdn.net/linhuanmars/article/details/24354291
这种方法更好,没有多余操作
Time: O(n), Space: 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; }}
0 0
- 2.2.4 Remove Duplicates from Sorted List
- 2.2.4—单链表—Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove duplicates from sorted list
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List
- 算法面试题
- Leetcode Interleaving String
- X窗口系统的协议和架构
- 呼呼呼呼呵呵呵呵呵
- 你你你你你您 我我我我我
- 2.2.4 Remove Duplicates from Sorted List
- 使用WM_MOUSEWHEEL
- hdu1525 Euclid's Game , 基础博弈
- MFC Static控件派生类,实现对函数图像的绘制。
- OpenCV3.0来啦
- [算法浅析] 用两个栈实现队列
- UVa10099_The Tourist Guide(最短路/floyd)(小白书图论专题)
- linux内核文档翻译 位置:Documentation/arm/Setup
- hdu 2147 kiki's game, 入门基础博弈