0
点赞
收藏
分享

微信扫一扫

[LeetCode]Remove Duplicates from Sorted List


Question
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.

Subscribe to see which companies asked this question

本题难度Easy。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
两种情况:

  1. ​cur.val==cur.next.val​​ ,删除cur.next
  2. ​cur.val!=cur.next.val​​,cur向后移一位

【附】
这题的思路我是从​​[LeetCode]Remove Duplicates from Sorted List II​​简化而来。写完后我有个疑问:第一种情况下,为什么cur不向后移动一位。然而我明白实际上cur兼有prev和cur的功能,删除了cur.next就是移动了cur。

【代码】

public class Solution {
public ListNode deleteDuplicates(ListNode head) {
//invariant
ListNode cur=head;
while(cur!=null&&cur.next!=null){
if(cur.val==cur.next.val){
cur.next=cur.next.next;
}else
cur=cur.next;
}
//ensure
return head;
}
}


举报

相关推荐

0 条评论