leetcode题解-83. Remove Duplicates from Sorted List
来源:互联网 发布:森汉机器人编程软件 编辑:程序博客网 时间:2024/06/04 01:39
题目:
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.
本题是给定了一个排序链表,然后删除其中重复的元素,因为已经排好序,所以我们只需要判断相邻元素是否相等即可。代码入下:
public ListNode deleteDuplicates(ListNode head) { ListNode list = head; while(list != null) { if (list.next == null) { break; } if (list.val == list.next.val) { list.next = list.next.next; } else { list = list.next; } } return head; }
此外,我们还可以使用递归函数来实现,代码入下:
public ListNode deleteDuplicates1(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; }
其实我一开始看这道题目的时候,没有注意到链表已经哦排序,所以使用的是下面这种方法,用Set来保存已经出现过的值,当再次出现时就删除节点。代码入下:
public ListNode deleteDuplicates2(ListNode head) { Set<Integer> s = new HashSet<Integer>(); ListNode cur = head; ListNode pre = new ListNode(0); pre.next = head; while(cur!=null){ if(s.contains(new Integer(cur.val))){ pre.next = cur.next; }else{ s.add(new Integer(cur.val)); pre = pre.next; } cur = cur.next; } return head; }
阅读全文
0 0
- LeetCode题解:Remove Duplicates from Sorted List
- LeetCode题解:Remove Duplicates from Sorted List
- Leetcode题解 83. Remove Duplicates from Sorted List
- leetcode题解-83. Remove Duplicates from Sorted List
- leetcode题解-83. Remove Duplicates from Sorted List
- [LeetCode]83.Remove Duplicates from Sorted List
- [Leetcode] 83. Remove Duplicates from Sorted List
- LeetCode --- 83. Remove Duplicates from Sorted List
- [leetcode] 83.Remove Duplicates from Sorted List
- LeetCode 83. Remove Duplicates from Sorted List
- 【leetcode】83. Remove Duplicates from Sorted List
- 83. Remove Duplicates from Sorted List LeetCode
- leetcode 83. Remove Duplicates from Sorted List
- [LeetCode]83. Remove Duplicates from Sorted List
- 【LeetCode】83. Remove Duplicates from Sorted List
- LeetCode 83. Remove Duplicates from Sorted List
- [leetcode] 83. Remove Duplicates from Sorted List
- leetcode 83. Remove Duplicates from Sorted List
- 基于Token的WEB后台认证机制
- 自定义一个控制输入小数或整数的位数的EditText
- spring bean初始化的完整生命周期
- matlab---文件路径操作
- 在Unity3D中用C#封装一个类似AS3的ByteArray类(二)--升级版
- leetcode题解-83. Remove Duplicates from Sorted List
- 修改Maven编译的JDK版本
- 基于VLC的播放器开发
- SDC沙盒技术
- java io
- Extract Interface(提炼接口)
- 无题
- PCL—低层次视觉—点云滤波(初步处理)
- HelloChart框架动态加载数据