创建一个方法,使用C#查找int数组中第二次出现的值

时间:2017-06-02 08:55:47

标签: c# arrays

对于家庭作业练习,我被要求创建一种方法来查找int数组中第二次出现的值。我能够找到第一次和最后一次,但由于某些未知的原因,我找不到第二次。我想要返回索引值,但我不能将它添加到最后,因为它说它不存在,我理解,因为它在循环外。我真的很沮丧请帮忙

public int SearchSecOccur(int[] arr, int sValue)
{
    int count = 0;

    for (int index = 0; index < arr.Length; index++)
    {
        if (arr[index] == sValue)
        {
            count++;
            if (count == 3)
            {
                return arr[index];
            }
        }  
    }   

    return index??;
}

2 个答案:

答案 0 :(得分:2)

如果你想找到第二次出现,为什么要停留在第四次?

if (count == 3)
{
   return arr[index];
}

您还返回值而非索引,请尝试以下操作:

if (count == 2)
{
   return index;
}

在方法结束时,您可能希望返回-1,因为没有第二个。

对于它的价值,一个适用于任何类型(泛型)的扩展,并允许指定您想要的索引的出现次数:

public static int IndexOfNthOccurence<T>(this IEnumerable<T> seq, T sValue, int numOccurence)
{
    int count = 0;
    int index = 0;
    var comparer = Comparer<T>.Default;

    foreach (T item in seq)
    {
        if (comparer.Compare(sValue, item) == 0) count++;
        if (count == numOccurence) return index;
        index++;
    }

    return -1;
}

答案 1 :(得分:0)

    public int SearchSecOccur(int[] arr, int sValue)
    {
      int count = 0;
      int ret_index = -1;

      for (int index = 0; index < arr.Length; index++)
        {
          if (arr[index] == sValue)
        {
          ret_index = index;
          count++;
          if (count == 2)
            {
              return ret_index;
            }
        }

        }
      return -1;
    }

如果发现第二次出现,那么它将返回其索引, 否则返回-1,即没有第二次出现。 在你的代码中,count == 3将返回第三次出现,而不是第二次出现,因为你将计数初始化为0。