Skip to content

Instantly share code, notes, and snippets.

@cds-amal
Created March 12, 2021 22:44
Show Gist options
  • Save cds-amal/d554256b8a0c0315d744655a98772f2a to your computer and use it in GitHub Desktop.
Save cds-amal/d554256b8a0c0315d744655a98772f2a to your computer and use it in GitHub Desktop.
/**
* @param {number[]} nums
* @return {number}
*/
const XXXremoveDuplicates = (nums) => { //{{{
if (nums.length === 0) return 0;
let last_item = nums[0];
let last_item_index = 0;
for (let i = 1; i < nums.length; i++) {
const current_item = nums[i];
if (last_item === current_item) {
console.log("dup", current_item, last_item, last_item_index, nums);
continue;
}
nums[last_item_index + 1] = current_item;
last_item_index++;
last_item = current_item;
console.log("loop", current_item, last_item, last_item_index, nums);
}
nums.length = last_item_index;
return nums.length;
}; //}}}
const removeDuplicates = (nums) => {
if (!nums.length) return 0;
let len = 1;
const lastNum = () => nums[len - 1];
for (let i = 1; i < nums.length; i++) {
const cn = nums[i];
// skip dupes
if (cn === lastNum()) continue;
// move successor number to end of list (eol) and update eol
nums[len++] = cn;
}
// Not sure if this needs to happen in the prompt
nums.length = len;
return len;
};
const rd = removeDuplicates;
let xs = [1, 2, 3, 4];
console.log(rd(xs));
console.log(xs);
xs = [1, 1, 2, 2, 2, 2, 2, 2, 3, 4, 5, 5, 5];
console.log(rd(xs));
console.log(xs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment