กำหนดอาร์เรย์ 3 ตัวที่เรียงลำดับจากน้อยไปมาก:
int[] one = {20, 35, 57, 70};
int[] two = {9, 35, 57, 70, 92};
int[] three = {25, 35, 55, 57, 67, 70};
ใช้ 3 ตัวชี้ (pointers) i, j, k เดินผ่านอาร์เรย์ทั้ง 3 พร้อมกัน:
- ถ้าค่าทั้ง 3 เท่ากัน → พบค่าซ้ำ พิมพ์ค่า และเพิ่ม i, j, k ทั้ง 3
- ถ้า one[i] < two[j] → เพิ่ม i
- ถ้า two[j] < three[k] → เพิ่ม j
- มิฉะนั้น → เพิ่ม 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
Complexity: O(n) โดย n คือความยาวอาร์เรย์ที่ยาวที่สุด เนื่องจากแต่ละ pointer เดินผ่านอาร์เรย์ของมันแค่ครั้งเดียว