[英]How to loop through integers from a given txt file and find 2nd largest number in c?
[英]How to find the 2nd largest number in the array, but return the last index that the value appears in?
我的实际问题是找到频率第二高的数据集中的数字。 我正在初始化一个数组,该数组是数据集中最大数字的大小,然后在数据出现在数据集中时递增数组中的相应索引。 如果两个以上的索引共享第二高的频率,那么我需要返回更大的索引。 在某些情况下,我的代码会返回正确的答案,但不是全部,我在逻辑中找不到错误。
int secondFreq(int data[], int maxNum){
int highest = 0;
int secondHighest = 0;
int x;
for(x = 0; x < maxNum; x++){
if(data[x] > data[highest]){
secondHighest = highest;
highest = x;
}
else if (data[x] > data[secondHighest]){
secondHighest = x;
}
else if (data[x] == data[secondHighest]){
secondHighest = x;
}
}
return secondHighest + 1;
}
以下是一个产生错误答案的数组示例。 左边的数字是索引,右边的数字是存储在该索引中的值。 我的函数返回12(第11个索引+ 1),但它应该返回5(第4个索引+ 1)。
0 - 2
1 - 2
2 - 5
3 - 2
4 - 5
5 - 4
6 - 2
7 - 2
8 - 6
9 - 4
10 - 3
11 - 6
12 - 2
13 - 2
14 - 3
在您的示例中,第二个'6'(索引11)将转到'else if(data [x]> data [secondHighest])'并将'secondHighest'更新为与'highest'相同。 该逻辑不能处理具有多个最高值的条件。 要修复,你可以在其他'else if'之前添加'else if(data [x] == data [highest])'。
但是,如果您的数据集如下,您将获得另一个不正确的anwser:
0 - 2
1 - 2
2 - 5
我将更改代码更清晰,更可读,如下所示:
int secondFreq(int data[], int maxNum){
int secondLargestValue = findsecondLargestValue(data);
return findIndexofValue(data, secondLargestValue) + 1;
}
int findsecondLargestValue(int data) {
...
}
int findIndexofValue(int data, int value) {
...
}
如果不考虑2次通过的效率考虑,(所以这不是最好的答案),我想说的是:
int secondFreq(int data[], int maxNum)
{
double highestVal = data[0]; // start with the first
// entry
int secondHighest = -1; // will send back 0 if everything
// ties for first
int x; // for loop index
for (x = 1; x < maxNum; x++) {
if (data[x] > highestVal) {
highestVal = data[x];
}
};
for (x = 1; x < maxNum; x++) {
if (data[x] != highestVal)
&&((secondHighest == -1) || (data[x] >= data[secondHighest])) {
secondHighest = x;
}
}
return secondHighest + 1;
}
虽然它看起来经历了两次,但它更难搞乱。
您的代码有两个问题:
highest = x;
在data[x] == data[highest]
。 secondHighest
最初应该是待定的。 以下是一个示例修改:
int secondFreq(int data[], int maxNum){
int highest = 0;
int secondHighest, secondFlag = 0;//secondFlag : Whether secondHighest has been determined, 0 : undetermined, 1(Not 0) : determined
int x;
for(x = 1; x < maxNum; x++){
if(data[x] > data[highest]){
secondHighest = highest;
highest = x;
secondFlag = 1;
}
else if (data[x] == data[highest]){
highest = x;
}
else if (secondFlag == 0 || data[x] >= data[secondHighest]){
secondHighest = x;
secondFlag = 1;
}
}
if(secondFlag)
return secondHighest + 1;
else
return 0;//All elements same
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.