c#刪除有序陣列中的重複項

yinghualeihenmei發表於2024-05-05

我寫的:

public int RemoveDuplicates(int[] nums) {
        int length=nums.Length;   
        int low=0;     
        for(int i=0;i<length;i++)
        {
            int num=nums[i];

              while(num!=nums[low])
              {
                nums[low+1]=num;
                low++;                                                                
              }             
        }
        return low+1;
    }

  別人用的雙指標:

public class Solution {
    public int RemoveDuplicates(int[] nums) {
        if(nums.Length == 0){return 0;}
        int slow = 0, fast = 1;
        while(fast < nums.Length){
            if(nums[fast] != nums[slow]){
                slow = slow + 1;
                nums[slow] = nums[fast];
            }
            fast = fast + 1;
        }
        return slow + 1;
    }
}


連結:https://leetcode.cn/problems/remove-duplicates-from-sorted-array/solutions/996194/kuai-man-zhi-zhen-26-shan-chu-you-xu-shu-8v6r/

  利用陣列的distinct()函式:

public class Solution
{
    public int RemoveDuplicates(int[] nums)
    {
        //if(nums.Length <= 1) return nums.Length;
        var nums2 = nums.Distinct();
        int n=0;
        foreach (var item in nums2){nums[n++] = item;}
        return n;
    }
}

  

相關文章