当前位置:网站首页>One question of the day - delete duplicates of the ordered array

One question of the day - delete duplicates of the ordered array

2022-06-11 21:57:00 Code loving students

Title Description :

To give you one An array arranged in ascending order nums , Please delete the repeated elements in place , Make each element appear only once , Returns the new length of the deleted array . The relative order of elements should be maintained Agreement .

Because the length of an array cannot be changed in some languages , So you have to put the result in an array nums The first part of . More formally , If there is... After deleting duplicates k Elements , that nums Before k An element should hold the final result .

Insert the final result into nums Before k Return to... After a position k .

Don't use extra space , You must be there. In situ Modify input array And using O(1) Complete with extra space .

Topic analysis :

For this problem, we can use the double pointer method to , Definition fast and slow Two pointers , If the array arr[fast]!=arr[fast-1] shows fast Is the boundary of non duplicates , Then its value can be assigned .

The code is as follows :

int removeDuplicates(int* nums, int numsSize){
        
       // from 1 It starts with the subscript 0 There is no need to delete the element of 
       int fast=1,slow=1;
       while(fast<numsSize){
        
        if(nums[fast]!=nums[fast-1]){
            nums[slow]=nums[fast];
            slow++;
           }
           fast++;
        }
       return size;  
}

原网站

版权声明
本文为[Code loving students]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112135378301.html