BM15 删除有序链表中重复的元素 - I

在这里插入图片描述
第一种解题思路:看到题目空间复杂度为O(1),时间复杂度为O(n),意味着只能遍历链表一次,而且不能声明额外的辅助空间,因此直接从第二个节点开始判断,因为是递增的,所以只需要判断node和head的最后一个节点是否一致就行了,如果val一致,那么node就继续往后寻找,直到找到不同的val,然后放到head的尾部,继续遍历node,最后node为null记得将head的尾部置空,否则会出现尾部还会有重复的没有过滤,这样就能做到时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode  node = head.next;
        ListNode  pre = head;
        while (node != null) {
            while (node != null && node.val == head.val) {
                node = node.next;
            }
            if (node == null) {
            	//记得将head的尾部置空
                head.next = null;
                break;
            }
            head.next = node;
            node = node.next;
            head = head.next;
        }
        return pre;
    }
}

第二种解题思路:只判断当前头节点是否和下一个头节点的val相同,相同就将next指向next的next,不相同就往下遍历,时间复杂度O(n),空间复杂度O(1)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode  pre = head;
        while (head != null) {
            if (head.next != null && head.val == head.next.val) {
                head.next = head.next.next;
            } else {
                head = head.next;
            }
        }
        return pre;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值