数据结构-02day
82. 删除排序链表中的重复元素 II (leetcode)
解题思路
暴力破解
- 先循环一次链表获取到重复的节点值,存入到ArryList中
- 再循环一次链表并循环ArrayList将有的节点一次删除
执行用时 :2 ms 内存消耗 :39.1 MB
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {
return null;
}
List<Integer> list = new ArrayList<>();
ListNode temp = new ListNode(0);
temp.next = head;
ListNode t = temp;
while(head.next != null) {
if(head.val == head.next.val) {
list.add(head.val);
while(head.next != null && head.val == head.next.val) {
head = head.next;
}
}else {
head = head.next;
}
}
while(temp.next != null && !list.isEmpty()) {
int num = list.get(0);
if(temp.next.val == num) {
while(temp.next.val == num && temp.next.next != null) {
temp.next = temp.next.next;
}
if(temp.next.val == num && temp.next.next == null) {
temp.next = null;
}
list.remove(0);
}else {
temp = temp.next;
}
}
return t.next;
}
}
暴力破解,内存和时间都消耗较大,我继续改进,也希望得到大家宝贵的意见