LC 1470.Shuffle the Array

题目描述

这是 LeetCode 上的 1470. 重新排列数组 ,难度为简单

给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。

请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。

示例 1:

1
2
3
输入:nums = [2,5,1,3,4,7], n = 3
输出:[2,3,5,4,1,7]
解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7]

示例 2:

1
2
输入:nums = [1,2,3,4,4,3,2,1], n = 4
输出:[1,4,2,3,3,2,4,1]

示例 3:

1
2
输入:nums = [1,1,2,2], n = 2
输出:[1,2,1,2]

提示:

  • 1 <= n <= 500
  • nums.length == 2n
  • 1 <= nums[i] <= 10^3

解答

方法一:模拟

根据题目描述,遍历一次的时候更新要返回数组的前 n 个数字的同时可以更新 n + i 位置的数字。

1
2
3
4
5
6
7
8
9
10
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] res = new int[2 * n];
for (int i = 0, j = 0; i < n; ++i) {
res[j++] = nums[i];
res[j++] = nums[n + i];
}
return res;
}
}
  • 时间复杂度\(O(n)\),遍历一半的 nums 数组,时间复杂度为 \(O(n)\)

  • 空间复杂度\(O(n)\)res 数组的长度为原数组长度 2n ,所以空间复杂度为 \(O(n)\)

每题一图


LC 1470.Shuffle the Array
https://chen-huaneng.github.io/2023/12/06/2023-12-6-2023-12-06-lc-1470/
作者
Abel
发布于
2023年12月6日
更新于
2023年12月6日
许可协议