题目
1470.
重新排列数组
给你一个数组 nums
,数组中有 2n
个元素,按
[x^{1},x^{2},...,x^{n},y^{1},y^{2},...,y^{n}]
的格式排列。
请你将数组按 [x^{1},y^{1},x^{2},y^{2},...,x^{n},y^{n}]
格式重新排列,返回重排后的数组。
示例 1:
输入: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:
输入:nums = [1,2,3,4,4,3,2,1], n = 4
输出:[1,4,2,3,3,2,4,1]
示例 3:
输入:nums = [1,1,2,2], n = 2
输出:[1,2,1,2]
提示:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
标签
数组
题解
【重新排列数组】简单模拟
依照题意模拟即可
1 2 3 4
| class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: return [a for i, j in zip(range(len(nums) // 2), range(len(nums) // 2, len(nums))) for a in (nums[i], nums[j])]
|
1 2 3 4
| class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: return [nums[i // 2 + (i % 2) * n] for i in range(2 * n)]
|
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public int[] shuffle(int[] nums, int n) { int[] arr = new int[n * 2]; for (int i = 0, j = n, k = 0; i < n; ) { arr[k++] = nums[i++]; arr[k++] = nums[j++]; } return arr; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { vector<int> arr(n * 2); for (int i = 0, j = n, k = 0; i < n; ) { arr[k++] = nums[i++]; arr[k++] = nums[j++]; } return arr; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
var shuffle = function(nums, n) { const arr = new Array(n * 2).fill(0); for (let i = 0, j = n, k = 0; i < n; ) { arr[k++] = nums[i++]; arr[k++] = nums[j++]; } return arr; };
|
- 时间复杂度: \(O(n)\)
- 空间复杂度: \(O(1)\)
如果对你有帮助的话,请给我点个赞吧~
欢迎前往 我的博客
或 Algorithm -
Github 查看更多题解