remove-duplicatesV2.js (915B)
1 //This is a better implementation that runs in linear time O(n). 2 //My other implementation required splicing of the array which reordered 3 //the entire array everytime a duplicate was found, but this way only 4 //unique values are saved to a new list then they are placed back in the 5 //input one. Another way to do this would be by using a set, but both 6 //implementations are the same in time complexity and space complexity. 7 //Runtime: 64ms Beats: 89.74% 8 //Memory: 44.6MB Beats: 68.36% 9 10 11 /** 12 * @param {number[]} nums 13 * @return {number} 14 */ 15 var removeDuplicates = function(nums) { 16 let l2 = [nums[0] , ]; 17 let vals = 1; 18 for(let i = 1 ; i < nums.length ; ++i){ 19 if(nums[i] == nums[i - 1]){ 20 continue; 21 } 22 else{ 23 l2[vals] = nums[i]; 24 vals += 1; 25 } 26 } 27 for(let i = 0 ; i < l2.length ; ++i){ 28 nums[i] = l2[i]; 29 } 30 return vals; 31 };