如何從排序的陣列中刪除重複元素並使用 C# 返回長度?


該陣列已排序,我們可以使用兩個指標 ii 和 jj,其中 ii 是慢指標,而 jj 是快指標。只要 nums[i] = nums[j]nums[i]=nums[j],我們增加 jj 來跳過重複項。

當我們遇到的 nums[j] != nums[i] 重複執行已經結束,所以我們必須複製它的值到 nums[i + 1]nums[i+1]。然後增加 ii,我們再次重複相同的過程,直到 jj 到達陣列末尾。

時間複雜度 − O(N)

示例

 即時演示

using System;
namespace ConsoleApplication{
   public class Arrays{
      public int RemoveDuplicatesFromSortedArrayAndReturnLength(int[] arr){
         int index = 1;
         for (int i = 0; i < arr.Length - 1; i++){
            if (arr[i] != arr[i + 1]){
               arr[index] = arr[i + 1];
               index++;
            }
            else{
               continue;
            }
         }
         return index;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
         int res = a.RemoveDuplicatesFromSortedArrayAndReturnLength(arr);
         Console.WriteLine(res);
         Console.ReadLine();
      }
   }
}

輸出

5

更新於: 2021 年 8 月 27 日

190 次瀏覽

開啟您的 職業生涯

完成課程獲取認證

開始學習
廣告
© . All rights reserved.