/**
* Two Pass Solution
* 自己的代码,看discussion也都是这样做的
* 不知道为什么时间空间效率却显示没有超过多少人
* Runtime: 144 ms, faster than 21.47%
* Memory Usage: 164.9 MB, less than 21.17%
*/
class Solution {
public ListNode deleteDuplicatesUnsorted(ListNode head) {
HashMap<Integer, Integer> map = new HashMap<>();
ListNode p = head, sentinel = new ListNode(-1), pre = sentinel;
sentinel.next = head;
while (p != null) {
map.put(p.val, map.getOrDefault(p.val, 0) + 1);
p = p.next;
}
p = head;
while (p != null) {
if (map.get(p.val) != 1) { // duplicate node
pre.next = p.next;
} else {
pre = p;
}
p = p.next;
}
return sentinel.next;
}
}
1836. Remove Duplicates From an Unsorted Linked List [Medium]
最新推荐文章于 2024-08-23 11:46:54 发布