首页  >  文章  >  后端开发  >  C# 程序在三个排序数组中查找公共元素

C# 程序在三个排序数组中查找公共元素

WBOY
WBOY转载
2023-09-12 11:17:021193浏览

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删除