使用C++编写代码,找到具有相同最小值和最大值的子数组的数量

PHPz
PHPz 转载
2023-08-25 23:33:09 915浏览

使用C++编写代码,找到具有相同最小值和最大值的子数组的数量

在本文中,我们将使用C++解决寻找最大值和最小值相同的子数组数量的问题。以下是该问题的示例−

Input : array = { 2, 3, 6, 6, 2, 4, 4, 4 }
Output : 12
Explanation : {2}, {3}, {6}, {6}, {2}, {4}, {4}, {4}, {6,6}, {4,4}, {4,4} and { 4,4,4 } are the subarrays which can be formed with maximum and minimum element same.

Input : array = { 3,3,1,5,1,2,2 }
Output : 9
Explanation : {3}, {3}, {1}, {5}, {1}, {2}, {2}, {3,3} and {2,2} are the subarrays which can be formed with minimum and maximum are the same.

求解的方法

通过示例,我们可以说,使用等于数组大小的相同最小和最大元素可以形成最小数量的子数组。如果连续的数字相同,子数组的数量可以更多。

所以我们可以采用遍历每个元素,检查其连续的数字是否相同的方法,如果连续的数字则增加计数相同,如果发现不同的数字则中断内循环。

每次内循环结束或中断时,结果变量都会增加结果变量,最后显示结果变量的结果。

p>

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
    int a[ ] = { 2, 4, 5, 3, 3, 3 };
    int n = sizeof(a) / sizeof(a[0]);
        int result = n, count =0;
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            if(a[i]==a[j])
                count++;
            else
                break;
        }
        result+=count;
        count =0;
    }
    cout << "Number of subarrays having minimum and maximum elements same:" << result;
    return 0;
}

输出

Number of subarrays having minimum and maximum elements same: 9
Time complexity = O(n2).

以上代码的解释

在这段代码中,我们使用变量n来存储数组的大小,result = n,因为最少可以形成n个子数组并计算相同数字的计数。

外部循环用于处理数组中的每个元素。内部循环用于查找索引元素之后有多少个连续相同的数字,并在内部循环结束时将计数变量与结果变量递增。最后显示存储在结果变量中的输出。

高效的方法

在这种方法中,我们遍历每个元素,并对于每个元素,我们搜索有多少个连续相同的数字。对于每个找到的相同数字,我们递增计数变量,并且当找到不同的数字时,通过使用公式"n = n*(n+1)/2"找到可以使用该公式形成多少个子数组,并将结果变量递增。

示例

#include <bits/stdc++.h>
using namespace std;
int main(){
    int a[] = { 2, 4, 5, 3, 3, 3 };
    int n = sizeof(a) / sizeof(a[0]);
        int result = 0;
    int count =1,temp=a[0];
    for (int i = 1; i < n; i++) {
        if (temp==a[i]){
            count++;
        }
        else{
            temp=a[i];
            result = result + (count*(count+1)/2);
            count=1;
        }
    }
    result = result + (count*(count+1)/2);
    cout <<  "Number of subarrays having minimum and maximum elements same:" << result;
    return 0;
}

输出

Number of subarrays having minimum and maximum elements same: 9
Time complexity : O(n)

上述代码说明

在此代码中,我们将数组的第 0 个索引存储在 temp 变量中,并从索引 1 开始循环。我们检查 temp 变量是否等于该元素在当前索引处,对于找到的相同数字将计数加 1。如果 temp 变量不等于索引元素,则我们找到可以通过相同数字的计数得出的子数组的组合,并将结果存储在 result 变量中。我们将临时值更改为当前索引,将计数重置为 1。最后,我们显示存储在结果变量中的答案。

结论

在本文中,我们解决了一个问题查找最小和最大元素相同的子数组的数量。我们还学习了解决这个问题的C++程序以及解决这个问题的完整方法(正常且高效)。我们可以用其他语言比如C、java、python等语言来编写同样的程序。希望这篇文章对您有所帮助。

以上就是使用C++编写代码,找到具有相同最小值和最大值的子数组的数量的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除