Example :
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums
being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
My code to solve this problem is
var removeDuplicates = function(nums) {
const non_duplicates = [];
for (let i=0;i<=nums.length-1;i++){
if(!(non_duplicates.includes(nums[i]))){
non_duplicates.push(nums[i]);
}
}
console.log(non_duplicates)
return non_duplicates.length;
};
That console.log(non_duplicates) displays correct output in stdOut. But when I return non_duplictes it prints empty array in output. And when I return non_duplictes.length it returns some array rather than the length of that array.
Please don't suggest any other method to solve this problem. Just tell what is wrong with this code
You can see that problem here
abozhilov :
Your solution doesn't modify the array inplace. That's the first problem.\nA bigger problem is that your algorithm is with O(N^2) time complexity, due to includes call and given that "1 <= nums.length <= 3 * 104" your solution would be incredibly slow if it ever passes the tests.\nThe goal is to find a linear solution of the problem. One possible solution would be:\nvar removeDuplicates = function(nums) {\n let j = 0;\n for (let i = 1, len = nums.length; i < len; i++) {\n if (nums[i] !== nums[j]) {\n nums[++j] = nums[i];\n }\n }\n \n return j + 1; \n};\n",
2022-08-01T21:22:06
Rohìt Jíndal :
You can achieve that by using Set() Object.\n\r\n\r\nlet nums = [0,0,1,1,1,2,2,3,3,4];\n\nconst uniqueNums = [...new Set(nums)];\n\nconsole.log(uniqueNums.length, uniqueNums);",
2022-08-02T12:39:56