LeetCode - 167. Remove Duplicates from Sorted Array




Thoughts:


I choose two pointer to solve this problem,

when I need to compare two values and the array is sorted.

The time complexity is O(n) for the iteration.



Thoughts visuzlization:


nums = [0,0,1,1,1,2,2,3,3,4]
i is right pointer, represented the cusor of current element
k is left pointer, represented the cursor that need to be checked with current value
if the value is different, move k pointer to right and do nums[k] = nums[i]
in the end, no matter the value is different or not, always move i pointer to right

[0,0,1,1,1,2,2,3,3,4] initial array, same value, move i pointer to right
 i
 k

[0,0,1,1,1,2,2,3,3,4] same value, move i pointer to right
   i
 k

[0,0,1,1,1,2,2,3,3,4] meet different value
     i
 k

[0,0,1,1,1,2,2,3,3,4] move k pointer to right
     i
   k

[0,1,1,1,1,2,2,3,3,4] do nums[k] = nums[i]
     i
   k

[0,1,1,1,1,2,2,3,3,4] move i pointer to right
       i
   k

...

repeat the process until the end of the array,
and the k pointer will be the index of the last element that is not duplicated,
so I need to do k + 1


Code:


/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  let k = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[k] !== nums[i]) {
      k++;
      nums[k] = nums[i];
    }
  }
  return k + 1;
};


Reference


Original link

Copyright © 2024 | All rights reserved.