Leetcode questions 26 and 27 — delete duplicates in an ordered array and remove elements

Time:2021-11-25

1. Leetcode question 26 delete duplicates in an ordered array

Requirements:

Give you an ordered array nums, please delete the repeated elements in place, make each element appear only once, and return the new length of the deleted array.

Do not use additional array space. You must modify the input array in place and complete it with O (1) additional space.
Example 1:
Input: num = [1,1,2]
Output: 2, Num = [1,2]
Explanation: the function should return a new length of 2, and the first two elements of the original array num are modified to 1 and 2. There is no need to consider the elements in the array that exceed the new length.

Example 2:
Input: num = [0,0,1,1,1,2,2,3,3,4]
Output: 5, Num = [0,1,2,3,4]
Explanation: the function should return a new length of 5, and the first five elements of the original array num are modified to 0, 1, 2, 3 and 4. There is no need to consider the elements in the array that exceed the new length.

For this problem, we can use the double pointer solution, whose time complexity is O (1), set two pointers, s (slow), f (fast), s initial is 0, f initial is 1, and change the next element of s according to the conditions.

if (nums[s] != nums[f]) {
        nums[s + 1] = nums[f];
        s++;
      }

Leetcode questions 26 and 27 -- delete duplicates in an ordered array and remove elements

 function print(nums) {
    let s = 0;
    for (let f = 1; f < nums.length; f++) {
      if (nums[s] != nums[f]) {
        nums[s + 1] = nums[f];
        s++;
      }
    }
    return s+1;
  }

2. Leetcode question 27 removing elements

Give you an array nums   And a value Val, you need to remove all values in place equal to   val   And returns the new length of the array after removal.
Instead of using extra array space, you must use only O (1) extra space and modify the input array in place.
The order of elements can be changed. You don't need to consider the elements in the array that exceed the new length.
Example 1:
Input: num = [3,2,2,3], Val = 3
Output: 2, Num = [2,2]
Explanation: the function should return a new length of 2, and the first two elements in num are 2. You don't need to consider the elements in the array that exceed the new length. For example, if the new length returned by the function is 2, and num = [2,2,3,3] or num = [2,2,0,0], it will also be regarded as the correct answer.

Example 2:
Input: num = [0,1,2,2,3,0,4,2], Val = 2
Output: 5, Num = [0,1,4,0,3]
Explanation: the function should return a new length of 5, and the first five elements in num are 0, 1, 3, 0 and 4. Note that these five elements can be in any order. You don't need to consider the elements in the array that exceed the new length.
  function print(nums) {
    let n = 0;
    for (let i = 0; i < nums.length; i++) {
      if (nums[i] != val) {
        nums[n] = nums[i];
        n++;
      }
    }
    return n;
  }