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
- 1 回答
- 0 关注
- 601 浏览
添加回答
举报