這裡我們會看到一個有趣的問題。我們有一個包含 N 個元素的陣列。我們必須執行一個查詢 Q,如下所示:
Q(start, end) 表示從開始到結束,數字「p」出現的次數剛好是「p」次。 p>
因此,如果數組類似於:{1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8},並且查詢為-
#Q(1 , 8) - 這裡1 出現一次,3 出現3 次。所以答案是 2
Q(0, 2) - 這裡 1 出現一次。所以答案是 1
query(s, e) -
Begin get the elements and count the frequency of each element ‘e’ into one map count := count + 1 for each key-value pair p, do if p.key = p.value, then count := count + 1 done return count; End
#include <iostream> #include <map> using namespace std; int query(int start, int end, int arr[]) { map<int, int> freq; for (int i = start; i <= end; i++) //get element and store frequency freq[arr[i]]++; int count = 0; for (auto x : freq) if (x.first == x.second) //when the frequencies are same, increase count count++; return count; } int main() { int A[] = {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8}; int n = sizeof(A) / sizeof(A[0]); int queries[][3] = {{ 0, 1 }, { 1, 8 }, { 0, 2 }, { 1, 6 }, { 3, 5 }, { 7, 9 } }; int query_count = sizeof(queries) / sizeof(queries[0]); for (int i = 0; i < query_count; i++) { int start = queries[i][0]; int end = queries[i][1]; cout << "Answer for Query " << (i + 1) << " = " << query(start, end, A) << endl; } }
Answer for Query 1 = 1 Answer for Query 2 = 2 Answer for Query 3 = 1 Answer for Query 4 = 1 Answer for Query 5 = 1 Answer for Query 6 = 0
以上是在C程式中,將數組範圍查詢與頻率相同的元素進行翻譯的詳細內容。更多資訊請關注PHP中文網其他相關文章!