leetcode 83. Remove Duplicates from Sorted List

257 篇文章 17 订阅

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) {
	if(head==null){
		return head;
	}
	int current=head.val;
	ListNode node=head;
	while(node.next!=null){
		while(node.next!=null&&node.next.val==current){
			node.next=node.next.next;			
		}
		if(node.next!=null){
			node=node.next;
			current=node.val;
		}
	}
	return head;
}
注意:为什么循环是用node.next循环,来判断node.next是否等于currentValue呢?因为只有在指针指向 重复结点的前一个结点 时,才能使用node.next=node.next.next来跳过重复结点。如果指针指向的是 重复结点,那么就没法删除重复结点。(有人说用node.val=node.next.val; node.next=node.next.next,可以把 重复结点 赋值为 重复结点的下一个结点,然后再跳过。但是这种方法只适用于重复结点 存在下一个结点 的情形,如果重复结点是链表的最后一个结点 就没有办法了,使用node=null没有用,必须要把重复结点的 上一个结点的next设为null。)
大神的解法跟我差不多,感觉很简洁。

public class Solution {
    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;
    }
}
这道题有solutions: https://leetcode.com/problems/remove-duplicates-from-sorted-list/solution/

Solution


Straight-Forward Approach [Accepted]

Algorithm

因为链表已经被排序,那么我们可以根据 某个结点的值 是否等于 它的下一个结点的值,来得出该结点是不是重复结点。

Java

public ListNode deleteDuplicates(ListNode head) {
    ListNode current = head;
    while (current != null && current.next != null) {
        if (current.next.val == current.val) {
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
    return head;
}

Complexity Analysis

The total run time is O(n)O(n), where nn is the number of nodes in the list.

Space complexity is O(1)O(1) since no additional space is used.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值