查詢三個有序陣列中的公共元素的C#程式


首先,初始化三個已排序的陣列 -

int []one = {20, 35, 57, 70};
int []two = {9, 35, 57, 70, 92};
int []three = {25, 35, 55, 57, 67, 70};

要查詢三個已排序陣列中的公共元素,請使用 while 迴圈遍歷陣列,並檢查第一個陣列與第二個陣列以及第二個陣列與第三個陣列 -

while (i < one.Length &amp;&amp; j < two.Length &amp;&amp; k < three.Length) {
   if (one[i] == two[j] &amp;&amp; two[j] == three[k]) {
      Console.Write(one[i] + " ");
      i++;j++;k++;
   }
   else if (one[i] < two[j])
      i++;
   else if (two[j] < three[k])
      j++;
   else
      k++;
}

示例

你可以嘗試執行以下程式碼,以查詢三個已排序陣列中的公共元素。

實際演示

using System;
class Demo {
   static void commonElements(int []one, int []two, int []three) {
      int i = 0, j = 0, k = 0;
      while (i < one.Length &amp;&amp; j < two.Length &amp;&amp; k < three.Length) {
         if (one[i] == two[j] &amp;&amp; two[j] == three[k]) {
            Console.Write(one[i] + " ");
            i++;j++;k++;
         }
         else if (one[i] < two[j])
            i++;
         else if (two[j] < three[k])
            j++;
         else
            k++;
      }
   }
   public static void Main() {
      int []one = {20, 35, 57, 70};
      int []two = {9, 35, 57, 70, 92};
      int []three = {25, 35, 55, 57, 67, 70};

      Console.Write("Common elements: ");

      commonElements(one, two, three);
   }
}

輸出

Common elements: 35 57 70 

更新時間: 2020-01-28

215 次瀏覽

啟動您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.