Algorithm Day 1: Removing Duplicates in Sorted Arrays

LeetCode question 26:

Given an ordered array nums, please delete repeated elements in place so that each element appears only once, and return the new length of the deleted array.
Don't use extra array space, you have to modify the input array in-place and do so using O(1) extra space.

Explanation:
Why is the returned value an integer, but the output answer is an array? Please note that the input array is passed by "reference", which means that modifying the input array in the function is visible to the caller.
You can imagine the internal operation as follows:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
for (int i = 0; i < len; i++) {
    
    
    print(nums[i]);
}

Example 1:

输入:nums = [1,1,2]
输出:2, nums = [1,2]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。

Example 2:

输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。

train of thought

  • Ordered array: repeated elements are in adjacent positions
  • The length of the final array is less than or equal to the original array
  • Because the "in-place" condition needs to be satisfied, no additional arrays must be created for brute-force copying
  • Just need to overwrite the duplicate position of the original array

Solution method:
Double pointer solution: the first pointer is used to scan the original array to find different elements, and the second pointer is used to change the position of different elements so that all elements in the final result array are different elements. Time
complexity : O(n)
Space Complexity: O(1)

class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    
          int slow=0;
         for(int i=0;i<nums.length;i++){
    
    
             if(nums[slow]!=nums[i]){
    
    
                 slow++;
                 nums[slow]=nums[i];
             }
             
         }
        
          return ++slow;
    }
}

Other application scenarios of the double-pointer solution: Obtaining a continuous array in the array is similar to the idea of ​​dichotomy. The double pointer solution brings different ideas to traversal


The above only represents the author's personal point of view, if you have any questions, please bear with me and tell the author in time. The question type is selected from leetcode, for reference only

Guess you like

Origin blog.csdn.net/qq_52696089/article/details/120461270