30:Remove Duplicates from Sorted List
来源:互联网 发布:java 微信 编辑:程序博客网 时间:2024/06/10 21:23
题目: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.
解题代码版本一:
//迭代版本//时间复杂度O(n),空间复杂度O(1)class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if (head == nullptr) return head; ListNode* prev = head; ListNode* cur = head -> next; while (cur != nullptr) { if (cur -> val == prev -> val) { prev -> next = cur -> next; delete cur; cur = prev -> next; } else { prev = prev -> next; cur = cur -> next; } } return cur; }};
解题代码版本二:
/递归版本//时间复杂度O(n),空间复杂度O(1)class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if (head == nullptr || head -> next == nullptr) return head; ListNode* p = head -> next; if (p -> val == head -> val) { while (p && head -> val == p -> val) { auto tmp = p; p = p -> next; delete tmp; } } head -> next = deleteDuplicates(p); return head; }};
0 0
- [leetcode]30 Remove Duplicates from Sorted List
- 30: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
- UVA-12563
- UVA-580
- 用Apache POI读取Excel并下载
- express 路由
- LeetCode:maximum-depth-of-binary-tree
- 30:Remove Duplicates from Sorted List
- lua + openresty web API 框架
- express.static 作用及用法
- linux下的静态库和动态库
- 树莓派新安装
- Linux下安装配置JavaJDK
- android 解析XML最常用的三种方式;DOM解析,SAX解析,PULL解析
- 字符串的反转
- HTTP协议