【问题标题】:k'th largest element in an array数组中的第 k 个最大元素
【发布时间】:2015-03-02 18:16:43
【问题描述】:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include<algorithm>

using namespace std;

bool findNthMax(double arr[], int len, int n, double& nth_max)
{

sort(arr, arr+n);


//Counter
int c = 1;

//Initialize nth max
nth_max = arr[0];

//Loop in the array while the count is less than (n)
for (int i = 0; i < len && c < n; i++)
{

    if (arr[i] != nth_max)
        c++;


    nth_max = arr[i];

}

return nth_max;

}

int main()
{
int n;
double arr[10];
double y;

cout << "The random array elements are:" << endl;

srand((unsigned)time(0));
for(int i=0; i<10; i++){
    arr[i] = (rand()%100);

    cout << arr[i] << ' ' ;

}

cout << endl;
cout << "Input a positive integer n: " ;
cin  >>  n ;

if(n>10)
cout << "The nth largest value does not exist." << endl;
else
cout << "The nth largest value is: " << findNthMax(arr, 10, n, y) << endl;

return 0;

}

编辑:如果第 n 个最大值不存在,该函数返回 false;第一个参数是输入数组;第二个参数是数组大小;第三个参数用于将 n 的值传递给函数;最后 参数是找到的第 n 个最大值。

主函数生成一个包含 10 个双随机元素的数组(在 [0, 99] 范围内。它打印出这 10 个元素。提示用户输入 正整数 n,然后打印出第 n 个最大值 数组。

我的输出如何显示第 n 大:当 n = 2 时为 1

【问题讨论】:

  • 你为什么返回 bool?
  • 不太清楚你在做什么。但是如果你传递长度为 n 的数组,那么应该总是有 m=n “最大”值。如果给出的数字大于元素的数量,则可以返回 false。对于其他情况,只需对数组进行排序并返回索引值我的值 m(m 最大)。
  • 您打印的是布尔返回值,而不是结果(写给y 会让人困惑,而返回值毫无意义,当然与描述不符)。我认为您想对整个数组进行排序,而不仅仅是第一个 n 元素,并且可能以相反的顺序。通常,您希望在调试器中单步执行代码,以查看它实际在做什么,以及它与您希望它做什么有什么不同。
  • 首先为什么你的函数的返回类型是bool。其次,为什么您只对数组的前 n 个元素进行排序?最后,循环做什么?

标签: c++ arrays algorithm


【解决方案1】:

您在 if arr[1] != nth_max 之后将 c 递增到 2。这意味着c !&lt; n,所以你for循环在2个循环后退出。

您需要对整个数组进行排序,b/c 您错过了在第二个最大值之前可能有 8 个重复项的情况,例如 { 8, 8, 8, 8, 8, 8, 8, 8, 1、2、8、8、8}。

sort(arr, arr+len);

您应该在数组末尾开始您的 for 循环...

nth_max = arr[len-1];    
for (int i = len-1; i >= 0 && c < n; i--)

然后在输出变量y之前也运行函数:

findNthMax(arr, 10, n, y);
cout << "The nth largest value is: " << y << endl;

【讨论】:

  • 这几乎可以正常工作,但就像你说的那样,我对数组的排序有问题。
  • @friedrojak 排序调用已添加到答案中。你几乎拥有它。
猜你喜欢
  • 2022-01-24
  • 2015-10-06
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多