C# 程式檢查兩個列表是否有至少一個公共元素


設定第一個列表。

int[] arr1 = {
   65,
   57,
   63,
   98
};

現在,設定第二個列表。

int[] arr2 = {
   43,
   65,
   33,
   57
};

現在,讓我們看看完整的程式碼,以檢查使用 == 和 < 運算子的兩個列表是否有公共元素。

示例

 即時演示

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {
   public static void Main() {
      int[] arr1 = {
         65,
         57,
         63,
         98
      };

      int[] arr2 = {
         43,
         65,
         33,
         57
      };

      // HashSet One
      var h1 = new HashSet < int > (arr1);
      // HashSet Two
      var h2 = new HashSet < int > (arr2);

      // Displaying
      int[] val1 = h1.ToArray();
      Console.WriteLine("Set one...");
      foreach(int val in val1) {
         Console.WriteLine(val);
      }

      //Displaying
      int[] val2 = h2.ToArray();
      Console.WriteLine("Set two...");
      foreach(int val in val2) {
         Console.WriteLine(val);
      }

      int i = 0, j = 0;
      Console.WriteLine("Common elements:");
      while (i < val1.Length && j < val2.Length) {
         if (val1[i] == val2[j]) {
            Console.Write(val1[i] + " ");
            i++;
            j++;
         } else if (val1[i] < val2[j])
         i++;
         else
         j++;
      }
   }
}

輸出

Set one...
65
57
63
98
Set two...
43
65
33
57
Common elements:
65 57

更新日期:22-06-2020

752 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.