我有以下类ListNode
class ListNode {
constructor(val) {
this.val = val
this.next = null
}
}
我试图通过将重复值存储在哈希中来删除重复值,如果存在这些值,则新的Node不应该由这些值组成;然而,我所完成的只是这份清单的副本。我不确定自己到底做错了什么。我的逻辑结构是否错误?
const deleteDuplicates = (head) => {
let newNode = new ListNode('dummy')
let current = newNode
let headHash = {}
while (head) {
if (headHash[head.val] === undefined) {
if (newNode.next === null) newNode.next = new ListNode(head.val)
else {
newNode = newNode.next
newNode.next = new ListNode(head.val)
}
}
headHash = (headHash[head.val] || 0) + 1
console.log(headHash, head.val);
head = head.next
}
return current.next
}
const l = new ListNode(1)
l.next = new ListNode(1)
l.next.next = new ListNode(2)
const l2 = new ListNode(1)
l2.next = new ListNode(1)
l2.next.next = new ListNode(2)
l2.next.next.next = new ListNode(3)
l2.next.next.next.next = new ListNode(3)
console.log(deleteDuplicates(l));
console.log(deleteDuplicates(l2));
有问题的行似乎是这样的:
headHash = (headHash[head.val] || 0) + 1
您必须将headHash
的当前head-value属性指定给一个未定义的值,而不是将整个headHash
分配给一个值。请参阅以下代码:
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
const deleteDuplicates = (head) => {
let newNode = new ListNode("dummy");
let current = newNode;
let headHash = {};
while (head) {
if (headHash[head.val] === undefined) {
if (newNode.next === null) {
newNode.next = new ListNode(head.val);
} else {
newNode = newNode.next;
newNode.next = new ListNode(head.val);
}
}
// headHash = (headHash[head.val] || 0) + 1 // <- offending line
headHash[head.val] = (headHash[head.val] || 0) + 1; // You need to assign the value to the headHash's key, not to the headHasn itself.
head = head.next;
}
return current.next;
};
const l = new ListNode(1);
l.next = new ListNode(1);
l.next.next = new ListNode(2);
const l2 = new ListNode(1);
l2.next = new ListNode(1);
l2.next.next = new ListNode(2);
l2.next.next.next = new ListNode(3);
l2.next.next.next.next = new ListNode(3);
console.log(deleteDuplicates(l));
console.log(deleteDuplicates(l2));