使用C++查詢所有元素都大於X的片段數量


在本文中,我們將找到給定序列中所有元素都大於給定數字X的片段或子陣列的數量。

我們只能計算一次重疊的片段,並且兩個連續的元素或片段不應該分別計數。以下是用此問題描述的基本示例:

Input : arr[ ] = { 9, 6, 7, 11, 5, 7, 8, 10, 3}, X = 7
Output : 3
Explanation : { 9 }, { 11 } and { 8, 10 } are the segments greater than 7

Input : arr[ ] = { 9, 6, 12, 2, 11, 14, 8, 14 }, X = 8
Output : 4
Explanation : { 9 }, { 12 }, { 11, 14 } and { 14 } are the segments greater than 8

尋找解決方案的方法

樸素方法

在這個問題中,我們用0初始化一個變數**state**,開始處理給定的陣列,當找到一個大於X的元素時將state更改為1,繼續處理元素,當找到小於或等於X的數字時將state更改回0,並且每次state從1變回0時,計數器加1。

示例

#include <bits/stdc++.h>
using namespace std;
int main (){
    int a[] = { 9, 6, 12, 2, 11, 14, 8, 14 };
    int n = sizeof (a) / sizeof (a[0]);
    int X = 8;
    int state = 0;
    int count = 0;
    // traverse the array
    for (int i = 0; i < n; i++){
        // checking whether element is greater than X
        if (a[i] > X){
           state = 1;
        }
        else{
           // if flag is true
           if (state)
               count += 1;
            state = 0;
        }
    }
    // checking for the last segment
    if (state)
        count += 1;
    cout << "Number of segments where all elements are greater than X: " << count;
    return 0;
}

輸出

Number of segments where all elements are greater than X: 4

上述程式的解釋

在上面的程式中,我們使用state作為開關,當找到大於X的數字時將其設定為1,當找到小於或等於X的數字時將其設定為0,並且每次state從1變回0時,計數器加1。最後,列印儲存在計數器中的結果。

結論

在本文中,我們透過設定state為1和0來解決查詢所有元素都大於X的片段數量的問題,無論何時找到一個片段。我們可以使用其他程式語言(如C、Java、Python等)編寫此程式。

更新於:2021年11月24日

252 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.