我想更改每個陣列的第一個和最后一個索引,因此這種情況下的輸出將是:[2,3,1],[9,4,6] [5,8,4]。
任何幫助將不勝感激!
static void Main(string[] args)
{
int[][] array1 =
{
new []{1,3,2},
new []{6,4,9},
new []{4,8,5}
};
foreach (int i in Snail(array1))
{
Console.WriteLine(i);
}
}
public static int[] Snail(int[][] array)
{
List<int> snail = new List<int>();
foreach (int[] list in array)
{
foreach (int i in list)
{
// how do I change place with first and last index
}
}
uj5u.com熱心網友回復:
您只需要一個回圈,因為您知道要操作的確切兩個索引
foreach (int[] list in array)
{
if (list.Length < 2) continue; //need 2 elements to swap
int temp = list[0]; //head is stored temporarily
list[0] = list[^1]; //swap happens
list[^1] = temp; //now set tail as temp value (the original head)
}
注意list[^1]和說的一樣list[list.Length - 1],都是最后一個元素的意思
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/524941.html
標籤:C#
