当前位置:网站首页>Remove duplicates from an ordered array

Remove duplicates from an ordered array

2022-06-13 00:56:00 -LM-

Remove duplicate items from an ordered array

Method 1 ( Two pointer thought )

Use cnt To record the subscript of the new array ,t To record every value added to the new array . First, you need to traverse the original array , The original array was ordered , Therefore, when the number is different from the previous one, it needs to be added to the new array , Then update t. Now t As the latest number to be compared , If the following sum t inequality , Then add it to the new array . The new array here is not redeclared , Instead, it replaces the original array ,cnt It is used to represent the subscript of the array updated each time , from 0 Start .

public static int removeDuplicates(int[] nums) {
    
        if(nums.length==0) return 0;
        int len = nums.length;
        int cnt=0;
        int t=nums[0];
        for(int i=0;i<len;i++){
    
            if(nums[i]!=t){
    
                cnt++;
                nums[cnt] = nums[i];
                t = nums[i];
            }
        }
        return cnt+1;
    }

Method 2 ( Double pointer )

Official explanation
Define two pointers \textit{fast}fast and \textit{slow}slow Fast pointer and slow pointer respectively , The fast pointer indicates the subscript position reached by traversing the array , The slow pointer indicates the subscript position to be filled in by the next different element , Initially, both pointers point to the subscript 11.

class Solution {
    
    public int removeDuplicates(int[] nums) {
    
        int n = nums.length;
        if (n == 0) {
    
            return 0;
        }
        int fast = 1, slow = 1;
        while (fast < n) {
    
            if (nums[fast] != nums[fast - 1]) {
    
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}
原网站

版权声明
本文为[-LM-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280557174694.html