【问题标题】:Two biggest of array C++ [duplicate]两个最大的数组 C++ [重复]
【发布时间】:2019-11-18 07:06:54
【问题描述】:

我有一个问题,看起来很简单,但我无法解决它给出了 n 个整数的数组。找到数组中最大的两个元素。我发现第一个找不到第二个。请帮我找到第二个。

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int a[n];
    for(int i=0;i<n;i++) {
        cin>>a[i];
    }

    int maks=a[0];
    for (int i=1;i<n;i++) {
        if(a[i]>maks) {
            maks=a[i];
        }
    }
    cout << maks;
}

【问题讨论】:

  • 需要在数组 C++ 中找到 2 个最大的元素。给定数组中的 5 个元素
  • 你甚至不需要一个数组来做到这一点,只是说。
  • 注意:变长数组are bad.
  • 答案已经是here
  • 是的,这确实很有效,并且使代码对我来说很清晰,非常感谢

标签: c++ arrays


【解决方案1】:

这是在数组中查找第二大元素的 sn-p,

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    int *a = new int[n];

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int top2element[2];
    if (a[0] > a[1]) {
        top2element[0] = a[0];
        top2element[1] = a[1];
    }
    else {
        top2element[1] = a[0];
        top2element[0] = a[1];
    }

    for (int i = 2; i < n; i++) {
        if (a[i] > top2element[0])
        {

            top2element[1] = top2element[0];
            top2element[0] = a[i];
        }
        else if (a[i] > top2element[1]) {
            top2element[1]= a[i];
        }
    }
    cout << top2element[0]<<endl;//biggest
    cout << top2element[1];//second biggest

    delete a;
}

注意:如果输入流的大小未知,则动态分配内存

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多