Array" challenge on leetcode. I ran the code on google dev tools and nothing was wrong. But leetcode says it is. Can somebody point out why is it so? Is it because I didn't fulfil the condition "you must do this by modifying the input array in-place with O(1) extra memory."? I haven't learnt big O notation yet, if so. Below is the code and screenshot:
var removeDuplicates = function(nums) {
for (let a of nums){
if (nums[nums.indexOf(a)] == nums[nums.lastIndexOf(a)] && nums.indexOf(a) !== nums.lastIndexOf(a)) {
nums.splice(nums.indexOf(a), nums.lastIndexOf(a)-nums.indexOf(a)) }
}
return nums;
};
Try this one: const removeDuplicates = (nums) => nums.sort().filter((value, index) => nums.indexOf(value) === index);
NEVER use for...of to loop through an array when the index is important. refer to the specification or the MDN docs for more.
Обсуждают сегодня