簡體   English   中英

C++:在數組中查找第二個最大元素

[英]C++: Finding second max element in array

我是新來的,正在學習 C++ 語言。 現在我必須找到數組中的第二大元素,但我的代碼有時沒有給我正確的輸出。 我有以下代碼來查找第二個最大元素。

for(int i = 0;i<size;i++)
{
    if(arr[i] > max)
    {
        second_max = max;
        max = arr[i];
    }
}

此代碼有時有效,有時它沒有給出第二個最大元素的正確值。 請幫助我我做錯了什么?

假設您正在找到maximumsecond_maximum元素,我注意到您正在跳過當arr[i]大於second_max但小於max時的場景,例如對於以下場景,您的代碼將無法正常工作

max: 15

second_max = 7

arr[i] = 12

將以下條件添加到第一個if條件下方的代碼中:

else if(arr[i] > second_max)
{
    second_max = arr[i];
}

這是僅使用標准算法的解決方案:

#include <iostream>
#include <vector>
#include <cassert>

int second_max(std::vector<int> v)
{
    using namespace std;

    sort(begin(v),
         end(v),
         std::greater<>());

    auto last = unique(begin(v),
                       end(v));

    auto size = last - begin(v);

    return (size == 0)
    ? 0
    : (size == 1)
    ? v[0]
    : v[1];
}


int main()
{
    using namespace std;

    cout << second_max({ 3,5,7,7,2,4,3,2,6 }) << endl;
    return 0;
}

而不是std::sort這應該用std::nth_element來完成。 這正是它設計的場景,並且當您只關心幾個元素時避免對整個集合進行排序。

你可以使用這個小程序。 我只使用 std 的標准算法,這是我能想到的最簡單的算法。

#include <array>
#include <algorithm>
#include <iostream>

int main()
{
    std::array<int, 10> ar = {1, 5, 15, 2, 3, 5, 6, 8, 9, 14};

    // Sort the array
    std::sort(std::begin(ar), std::end(ar));

    // Print the second max element
    std::cout << ar[ar.size() - 2];
}

您的 if 語句的邏輯不完整。 這是工作版本:

  for(int i = 0; i<size; i++)
  {
    if(max < arr[i]) {
      second_max = max;
      max = arr[i];
    }
    else if(second_max < arr[i])
      second_max = arr[i];
  }

我的解決方案:

#include <stdio.h>
#include <limits.h>

/**
 * get second max of array
 * @param arr the Array
 * @param len the array length
 * @return return second max if searched otherwise return -1
 */
int getSecondMax(const int *arr, int len) {
    int secondMax = INT_MIN; //-2147483647 - 1
    int max = INT_MIN + 1;
    for (int i = 0; i < len; ++i) {
        if (arr[i] > max) {
            secondMax = max;
            max = arr[i];
        } else if (arr[i] > secondMax && arr[i] != max) {
            secondMax = arr[i];
        }
    }
    return secondMax != INT_MIN + 1 ? secondMax : -1;
}

int main() {
    int arr[] = {0, 3, -1, 4, 5};
    int len = sizeof(arr) / sizeof(arr[0]);

    int secondMax = getSecondMax(arr, len);
    secondMax != -1 ? printf("the second max = %d\n", secondMax) : printf("not found second max\n");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM