প্রথমে তিনটি সর্টেড অ্যারে ইনিশিয়ালাইজ করুন:
int[] one = {20, 35, 57, 70};
int[] two = {9, 35, 57, 70, 92};
int[] three = {25, 35, 55, 57, 67, 70};
তিনটি সর্টেড অ্যারেতে কমন এলিমেন্ট বের করতে একই সময় তিনটি অ্যারে ইটারেট করুন এবং প্রথম অ্যারেক দ্বিতীয়ের সাথে, দ্বিতীয়কে তৃতীয়ের সাথে তুলনা করুন:
while (i < one.Length && j < two.Length && k < three.Length) {
if (one[i] == two[j] && 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 && j < two.Length && k < three.Length) {
if (one[i] == two[j] && 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
টাইম কমপ্লেক্সিটি: O(n1 + n2 + n3) - লিনিয়ার টাইম।