1 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
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;
}
作為一個(gè)可運(yùn)行的小提琴:https ://dotnetfiddle.net/TfjPuY
- 1 回答
- 0 關(guān)注
- 567 瀏覽
添加回答
舉報(bào)