[LeetCode]Remove Duplicates from Sorted List

来源:互联网 发布:yum 卸载 编辑:程序博客网 时间:2024/06/03 13:50

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 0
原创粉丝点击