1 回答

TA贡献1847条经验 获得超11个赞
违规行似乎是这一行:
headHash = (headHash[head.val] || 0) + 1
您不必将整体分配headHash给一个值,而是必须将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));
添加回答
举报