题解 | 删除有序链表中重复的元素-II
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
利用数组进行存储链表内元素出现的频次,最后进行拼接
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * {1,2,2} => {1} * {} => {} * {1,1,1} => {} * {2,2,3} => {3} * * @param head ListNode类 * @return ListNode类 */ function deleteDuplicates(head) { // write code here let arr = []; while (head) { const t = arr.find((e) => e.val === head.val); if (t) { t.num++; } else { arr.push({ val: head.val, num: 1 }); } head = head.next; } let p = new ListNode(); let res = p; arr.forEach((e) => { if (e.num === 1) { res.next = new ListNode(e.val); res = res.next; } }); return p.next; } module.exports = { deleteDuplicates: deleteDuplicates, };