为了账号安全,请及时绑定邮箱和手机立即绑定

在 C# 中的数组中查找子数组

在 C# 中的数组中查找子数组

C#
跃然一笑 2022-10-23 16:31:36
我试图在数组中找到子数组。它仅适用于一个子数组,但我希望如果有多个子数组,它会返回最后一个的索引。例如,对于 [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;    }}
查看完整描述

1 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

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


查看完整回答
反对 回复 2022-10-23
  • 1 回答
  • 0 关注
  • 601 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号