亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 611 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號