You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何交换二维数组中每个子数组的首尾元素(C#实现)

二维数组子数组首尾元素交换实现方案

完整实现代码

你可以在Snail方法中先完成每个子数组的首尾元素交换,再将处理后的元素收集到列表中返回。以下是完善后的代码:

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)
    {
        // 交换当前子数组的首尾元素
        if (list.Length > 0)
        {
            int temp = list[0];
            list[0] = list[list.Length - 1];
            list[list.Length - 1] = temp;
        }
        // 将交换后的元素加入结果列表
        foreach (int i in list)
        {
            snail.Add(i);
        }
    }
    return snail.ToArray();
}

关键逻辑说明

  1. 首尾交换操作:通过临时变量temp存储第一个元素,再将最后一个元素赋值给第一个位置,最后把临时变量的值放到最后一个位置,完成交换。
  2. 空数组兼容:判断子数组长度大于0再执行交换,避免空数组访问索引报错。
  3. 结果收集:交换完成后遍历子数组,将所有元素加入列表,最后转为数组返回。

不修改原数组的替代方案

如果需要保留原数组的原始数据,可以不修改原数组,直接按交换后的顺序收集元素:

public static int[] Snail(int[][] array)
{
    List<int> snail = new List<int>();
    foreach (int[] list in array)
    {
        if (list.Length == 0) continue;
        
        // 先添加最后一个元素
        snail.Add(list[list.Length - 1]);
        // 添加中间元素(存在的话)
        for (int j = 1; j < list.Length - 1; j++)
        {
            snail.Add(list[j]);
        }
        // 最后添加第一个元素
        snail.Add(list[0]);
    }
    return snail.ToArray();
}

内容的提问来源于stack exchange,提问作者Max Andersson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:01:13