![](/img/trans.png)
[英]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.