[英]Finding the last repetition index of element in array
如何在C#中检索数组中元素的最后一个重复索引?
例如,您有: int[] array = { 3, 5, 7, 8, 3, 4, 3 , 9 };
您正在搜索元素3,其中最后一个重复的索引为6。
这是我找到第一次重复的方法:
public static int Search(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (value == array[i])
{
return i;
}
}
return -1;
}
PS:我不能使用任何功能或方法。 我只允许使用数组。
尝试从后面搜索。 如果从数组的第一个元素开始搜索,则肯定需要搜索直到数组的末尾。 如果从后面搜索,找到后就可以直接返回该值。
public static int search(int lem, int[] a)
{
for (int i = a.Length - 1; i >= 0; i--)
{
if (lem == a[i])
{
return i;
}
}
return -1;
}
您的问题含糊不清。 如果您正在寻找任何重复项 (不必要3
),建议使用HashSet<int>
(C#实现):
int[] array = { 3, 5, 7, 8, 3, 4, 3, 9 };
HashSet<int> used = new HashSet<int>();
int last = -1;
for (int i = 0; i < array.Length; ++i)
if (!used.Add(array[i])) // failed to add to the set, array[i] is a duplicate
last = i;
Console.Write(last);
如果您只是在寻找3
的最后一次出现,请尝试向后循环:
int last = -1;
for (int i = array.Length - 1; i >= 0; --i)
if (array[i] == 3) {
last = i;
break;
}
如果您知道如何查找第一个重复,为什么不使用array.Reverse()
,使用已知的算法,然后从array.Length
减去找到的值?
但是,如果只需要一个方法调用,则可以修改解决方案,直到完成循环遍历数组后才返回该值:
public static int search(int lem, int[] a)
{
int j = -1;
for (int i = 0; i < a.Length; i++)
{
if (lem == a[i])
{
j = i;
}
}
return j;
}
尝试以下通用方法:
public static int FindLast<T>(T[] array, T value)
where T : IEquatable<T>
{
for (int i = array.Length - 1; i >= 0; i--)
{
if (array[i].Equals(value))
{
return i;
}
}
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.