Given the array nums
consisting of 2n
elements in the form [x1,x2,...,xn,y1,y2,...,yn]
.
Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2]
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
重新排列数组。
给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。
请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shuffle-the-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题我感觉是在考察一个人对于数组 index 之间发生倍数关系是否敏感。题目说数组的长度是 2n,那么数组的长度一定是偶数,所以遍历的时候只要遍历原数组长度的一半即可。而且题目虽然给了变量 n,但是其实用不上,因为 n = len / 2。
时间O(n)
空间O(n)
Java实现
class Solution { public int[] shuffle(int[] nums, int n) { int len = nums.length; int[] res = new int[len]; for (int i = 0; i < len / 2; i++) { res[2 * i] = nums[i]; res[2 * i + 1] = nums[i + len / 2]; } return res; } }
标签:...,Shuffle,nums,int,1470,数组,y1,Array,y2 From: https://www.cnblogs.com/cnoodle/p/16635828.html