preface

About the LeetCode array type problem related solutions, it can be seen that LeetCode array type problem before doing must see, classification solution summarized the problem, can be used to improve a single. If you think it is helpful, remember to give more likes and attention, thank you!

Topic describes

Given an ordered array nums, remove the repeated elements in place so that each element appears only once and return the new length of the deleted array.

Instead of using extra array space, you must modify the input array in place and do so using O(1) extra space.

Example 1: Input: nums = [1,1,2] Output: 2, nums = [1,2] Explanation: The function should return the new length 2, and the first two elements of the original array nums are changed to 1,2. You don’t need to worry about elements beyond the new length of the array.

Example 2: Input: nums = [0,0,1,1,1,2,2,3, 4] Output: 5, nums = [0,1,2,3,4] Explanation: The function should return the new length 5, and the first five elements of the original array NUMs are modified to 0,1,2,3,4. You don’t need to worry about elements beyond the new length of the array.

Link: leetcode-cn.com/problems/re…

Answer key

  1. In the double-pointer method, the fast and slow Pointers point to the current array position and the result array position respectively. If the fast and slow Pointers point to different numbers, new elements need to be added to the result array. The time complexity is order n.
/ * * *@param {number[]} nums
 * @return {number}* /
var removeDuplicates = function(nums) {
    const n = nums.length
    if (n < 2) return n
    let slow = 0 
    let fast = 1
    while (fast < n) {
      if(nums[fast] ! == nums[slow]) { ++slow nums[slow] = nums[fast] } ++fast }return slow+1
};
Copy the code