此代码查找最高编号和第二高编号但提供错误的索引编号,但仅在某些情况下 数组值时:{1,3,3,0,3} 当数组值:{3,3,0,1,2}
时如果所有都是唯一的数字,那么它会给出准确的答案和准确的索引值;我需要在哪里更改代码以获得上述案例的准确索引值?
FirstMaxNumber=arrFindIndex[0];
SecondMaxNumber=arrFindIndex[0];
FirstMaxRatingIndex=0;
SecondMaxRatingIndex=0;
for (int i = 0; i < arrSize; i++)
{
if (FirstMaxNumber <= arrFindIndex[i])
{
SecondMaxNumber = FirstMaxNumber;
FirstMaxNumber = arrFindIndex[i];
FirstMaxRatingIndex = i;
}
else if (SecondMaxNumber <= arrFindIndex[i])
{
SecondMaxNumber = arrFindIndex[i];
SecondMaxRatingIndex = i;
}
}
// print(FirstMaxNumber);
// Print(FirstMaxRatingIndex);
// print(SecondMaxNumber);
// print(SecondMaxRatingIndex);
答案 0 :(得分:1)
在第一个if语句中,设置第二个最大值的值:
SecondMaxNumber = FirstMaxNumber;
但索引不是:
SecondMaxRatingIndex = FirstMaxRatingIndex;
FirstMaxRatingIndex = i;
答案 1 :(得分:0)
这样的事情:
FirstMaxNumber = arrFindIndex[0];
SecondMaxNumber = arrFindIndex[0];
FirstMaxRatingIndex = 0;
SecondMaxRatingIndex = 0;
// Do not use magic values: "arrSize" but actual length: arrFindIndex.Length
for (int i = 1; i < arrFindIndex.Length; i++) {
int v = arrFindIndex[i];
if (v > FirstMaxNumber) {
// so "first" becomes "second"
SecondMaxNumber = FirstMaxNumber;
SecondMaxRatingIndex = FirstMaxRatingIndex;
FirstMaxNumber = v;
FirstMaxRatingIndex = i;
}
else if ((v > SecondMaxNumber) || (i == 1)) {
SecondMaxNumber = v;
SecondMaxRatingIndex = i;
}
}
答案 2 :(得分:0)
为什么不直接使用LINQ?
var arr = new [] {3, 0, 4, 2, 3, 7};
var min = arr.Select((Val, Key) => new { Val, Key }).First(x => x.Val == arr.Min());
var max = arr.Select((Val, Key) => new { Val, Key }).First(x => x.Val == arr.Max());
Console.WriteLine($"Min Key: {min.Key} Val: {min.Val} \nMax Key: {max.Key} Val: {max.Val}");
// Output
// Min Key: 1 Val: 0
// Max Key: 5 Val: 7
答案 3 :(得分:0)
如果阵列很短并且您并不特别关心它的速度有多快,那么最简单的代码是这样的:
var indices = Enumerable.Range(0, array.Length).ToArray();
Array.Sort(array, indices, Comparer<int>.Create((a, b) => b - a));
然后indices
将按降序包含所有元素的索引,因此您只需要前两个。
这是一个可编辑的控制台应用程序(需要.Net 4.5或更高版本):
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
static class Program
{
static void Main()
{
test(1, 3, 3, 0, 3); // Prints 1, 2
test(3, 3, 0, 1, 2); // Prints 0, 1
}
static void test(params int[] array)
{
var indices = Enumerable.Range(0, array.Length).ToArray();
Array.Sort(array, indices, Comparer<int>.Create((a,b)=>b-a));
Console.WriteLine($"{indices[0]}, {indices[1]}");
}
}
}