ได้รับอาร์เรย์ตัวเลขต่อเนื่อง (consecutive) ความยาว n มีตัวเลขเพียงตัวเดียวที่ซ้ำมากกว่า 1 ครั้ง ต้องการหาจำนวนครั้งที่ตัวเลขนั้นซ้ำ
ตัวอย่าง
อินพุต: arr[] = {0, 1, 2, 3, 3, 3}, N = 6
เอาต์พุต: 3 (เลข 3 ซ้ำ 3 ครั้ง)
อินพุต: arr[] = {1, 2, 3, 4, 4, 4, 4, 4, 5, 6}, N = 10
เอาต์พุต: 5 (เลข 4 ซ้ำ 5 ครั้ง)
แนวทาง
- วนลูป
iจาก 0 ถึง n-1 - ถ้า
arr[i] == arr[i+1]เพิ่มตัวนับและบันทึกค่า - หลังลูปเพิ่มตัวนับอีก 1 สำหรับตัวสุดท้ายของกลุ่มที่ซ้ำ
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
void findRepeat(int arr[], int n) {
int count = 0;
int value = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == arr[i+1]) {
count++;
value = arr[i];
}
}
count++; // สำหรับตัวสุดท้าย
cout << "Repeated Element: " << value;
cout << endl << "Number of occurrences: " << count;
}
int main() {
int Arr[] = {2, 3, 4, 5, 5, 5, 6, 7, 8};
int len = sizeof(Arr) / sizeof(Arr[0]);
findRepeat(Arr, len);
return 0;
}
ผลลัพธ์
Repeated Element: 5 Number of occurrences: 3