เราได้รับอาเรย์จำนวนเต็มที่เป็น sorted rotated array เป้าหมายคือหาจำนวนสมาชิกที่น้อยกว่าหรือเท่ากับ K วิธีการคือลูปผ่านทั้งอาเรย์นับสมาชิกที่ <= K
อินพุต
Arr[] = {1, 2, 3, 4, 9, 8, 10} K = 4
เอาต์พุต
Elements less than or equal to 4: 4
คำอธิบาย − สมาชิก <=4: 1,2,3,4 Count=4
อินพุต
Arr[] = {5, 3, 6, 1, 8, 100, 12, 31} K = 3
เอาต์พุต
Elements less than or equal to 3: 2
คำอธิบาย − สมาชิก <=3: 1,3 Count=2
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- อาเรย์ Arr[] และ K
- n = ความยาวอาเรย์
- count = 0
- ลูป i=0..n-1 ถ้า Arr[i] <= K count++
- พิมพ์ count
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int Arr[] = {4, 5, 8, 1, 3, 7, 10, 9, 11};
int k = 7;
int n = sizeof(Arr) / sizeof(Arr[0]);
int count = 0;
for (int i = 0; i < n; i++)
if (Arr[i] <= k)
count++;
cout << "Elements less than or equal to " << k << " in given sorted rotated array: " << count;
return 0;
}
ผลลัพธ์
Elements less than or equal to 7 in given sorted rotated array: 5