首頁  >  文章  >  後端開發  >  C# 程式在三個排序數組中尋找公共元素

C# 程式在三個排序數組中尋找公共元素

WBOY
WBOY轉載
2023-09-12 11:17:021220瀏覽

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 

以上是C# 程式在三個排序數組中尋找公共元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除