使用C++编写,找出所有元素都大于X的段的数量

使用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 的元素时,将状态更改为 1,并继续处理元素;当找到小于或等于 X 的数字时,将状态更改回 0,每次状态变为 1 并返回时,将 count 增加 1到 0。

示例

#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

上述程序说明

在上面的程序中,我们使用状态作为开关,当找到大于 X 的数字时将其设置为 1,当找到大于 X 的数字时将其设置为 0找到小于或等于 X 的数字,每次状态变为 1 并返回到 0 时,我们将计数加 1。最后,打印存储在计数中的结果。

结论 h2>

在本文中,我们通过应用每当找到段时将状态设置为 1 和 0 的方法解决查找所有元素都大于 X 的段数的问题。我们可以用任何其他编程语言(例如 C、Java、Python 等)编写此程序。

以上就是使用C++编写,找出所有元素都大于X的段的数量的详细内容,更多请关注编程之家其它相关文章

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...