[leetcode]Remove Duplicates from Sorted List II

136 篇文章 0 订阅
117 篇文章 0 订阅

新博文地址:[leetcode]Remove Duplicates from Sorted List II

http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

 

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

 我的想法还是很简单,遇到与后继节点相同的节点,就把其后驱节点删掉,并将该节点标记为should delete,时间复杂度为O(n),边界情况:当节点为最后一个节点时,应该找到其前驱节点。

我用了两种方法实现,一种不改变list结构,重新生成一个list,即空间复杂度O(n)

另一种直接在原list上进行操作,空间复杂度O(1)。

第一种:

 public ListNode deleteDuplicates(ListNode head) {
		if (head == null || head.next == null) {
			return head;
		}
		ListNode tail = head;
		List<Integer> list = new ArrayList<Integer>();
		boolean delete = false;
		while (tail != null) {
			if (tail.next != null && tail.val != tail.next.val) {
				if(!delete){
					list.add(tail.val);
				}else{
					delete = false;
				}
			}else{
				delete = true;
			}
			tail = tail.next;
			if(tail.next == null){
				if(!delete){
					list.add(tail.val);
				}
				break;
			}
		}
		ListNode newHead = new ListNode(0);
		ListNode newTail = newHead;
		for(Integer tem : list){
			ListNode node = new ListNode(tem);
			newTail.next = node;
			newTail = node;
		}
		return newHead.next;
    }

 

第二种:
    public ListNode deleteDuplicates(ListNode head) {
		if (head == null || head.next == null) {
			return head;
		}
		ListNode tail = head;
		boolean delete = false;
		while (tail.next != null) {
			if (tail.val == tail.next.val) {
				delete = true;
				tail.next = tail.next.next;
			} else {
				if (!delete) {
					tail = tail.next;
				} else {
					tail.val = tail.next.val;
					tail.next = tail.next.next;
					delete = false;
				}
			}
		}

		ListNode tem = head;
		if (delete) {
			if (tail == head) {
				return null;
			} else {
				while (tem.next != tail) {
					tem = tem.next;
				}
				tem.next = null;
			}
		}
		return head;
	}
 

代码还是一如既往的长,不够简练啊。。。。囧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值