给定由2n个元素组成的数组nums,其形式为[x1,x2,…,xn,y1,y2,…,yn]
以[x1,y1,x2,y2,…,xn,yn]的形式返回数组。
示例1:
输入:nums = [2,5,1,3,4,7], n = 3
输出:[2、3、5、4、1、7]
public int[] Shuffle(int[] nums, int n) {
int[] result = new int[nums.Length];
int z = 0;
for (int x = 0; x < (2 * n); x += 2) {
result[x] = nums[z];
z++;
}
z = 0;
for (int y = n; y < (2 * n); y++) {
result[z + 1] = nums[y];
z += 2;
}
return result;
}
好了:
void Main()
{
var nums = new[] { 2, 5, 1, 3, 4, 7 };
var result = Shuffle(nums, 3);
Console.WriteLine(String.Join(",", result));
}
public int[] Shuffle(int[] nums, int n) =>
nums
.Take(n)
.Zip(nums.Skip(n), (x, y) => new[] { x, y })
.SelectMany(z => z)
.ToArray();
这给了我:
2,3,5,4,1,7
或:
public int[] Shuffle(int[] nums, int n) =>
(
from zs in nums.Take(n).Zip(nums.Skip(n), (x, y) => new[] { x, y })
from z in zs
select z
).ToArray();
您可以计算出哪个项目应该放在i
-th索引:
public static int[] Shuffle(int[] nums) {
// Since we have public method, we should validate input
if (null == nums)
throw new ArgumentNullException(nameof(nums));
if (nums.Length % 2 != 0)
throw new ArgumentOutOfRangeException(nameof(nums));
int[] result = new int[nums.Length];
// All we have to do is to place right item at i-th index:
for (int i = 0; i < nums.Length; ++i)
result[i] = nums[i / 2 + (i % 2) * (nums.Length / 2)];
return result;
}
注意,我们可以去掉n
,因为我们可以很容易地将其计算为n == nums.Length / 2
。
同样的想法通过Linq实现:
public static int[] Shuffle(int[] nums) {
if (null == nums)
throw new ArgumentNullException(nameof(nums));
if (nums.Length % 2 != 0)
throw new ArgumentOutOfRangeException(nameof(nums));
return Enumerable
.Range(0, nums.Length)
.Select(i => nums[i / 2 + (i % 2) * (nums.Length / 2)])
.ToArray();
}