【问题标题】:Find subarray in array in C#在 C# 中的数组中查找子数组
【发布时间】:2019-08-04 14:54:08
【问题描述】:

我试图在数组中查找子数组。它只适用于一个子数组,但我希望如果有多个子数组,它会返回最后一个的索引。例如,对于 [3,4,1,2,0,1,2,5,6] 和 [1,2] 应该返回 5。

public int FindArray(int[] array, int[] subArray)
    {
        //throw new NotImplementedException();
    int y=0;
    int index=0;
    bool find= false;
    for(int x=0;x< array.Length && y< subArray.Length;)
    {
        if(array[x]!= subArray[y])
        {
            if(find==true)
            {               
                y=0;
                index=x;
            }
            else
            {
                x++;                
                y=0;
                index=x;    
            }
        }
        else
        {
            find=true;
            x++;        
            y++;
        }
    }

    if(y==subArray.Length)
            return index;
    else
            return -1;
    }
}

【问题讨论】:

  • 从数组末尾开始搜索,例如for (int x = array.Length - 1; x &gt;= 0 ...)
  • 我尝试过(并写了 x-- 而不是 x++),但随后它在 if(find==true) 处进入无限循环,因为它永远不会减少 x。但是之前没有 x++ 也可以工作。

标签: c# arrays


【解决方案1】:
public int FindLast(int[] haystack, int[] needle)
{
    // iterate backwards, stop if the rest of the array is shorter than needle (i >= needle.Length)
    for (var i = haystack.Length - 1; i >= needle.Length - 1; i--)
    {
        var found = true;
        // also iterate backwards through needle, stop if elements do not match (!found)
        for (var j = needle.Length - 1; j >= 0 && found; j--)
        {
            // compare needle's element with corresponding element of haystack
            found = haystack[i - (needle.Length - 1 - j)] == needle[j];
        }
        if (found)
            // result was found, i is now the index of the last found element, so subtract needle's length - 1
            return i - (needle.Length - 1);
    }
    // not found, return -1
    return -1;
}

作为一个可运行的小提琴:https://dotnetfiddle.net/TfjPuY

【讨论】:

  • 你能把“var found = true”改成“bool found = true”吗
  • 谢谢。我认为这是一种算法。它有名字吗?
  • Christoph 的算法 :-) 不,开个玩笑。我不知道。我刚想出来。
  • 我喜欢它。我认为这个解决方案也适用于 Java。 :)
  • 如果我没记错的话,var.length() 除外。好久没学Java了。
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多