【2022-08-29每日一题】1470. 重新排列数组
2022-08-29
2分钟阅读时长
2022-08-29每日一题:1470. 重新排列数组
- 难度:Easy
- 标签:数组
给你一个数组 nums
,数组中有 2n
个元素,按 [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] 解释:由于 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
// 写法一
func shuffle(nums []int, n int) []int {
ans := make([]int, 2 * n)
for i := 0; i < n; i++ {
ans[2*i] = nums[i]
ans[2*i+1] = nums[n+i]
}
return ans
}
// 写法二
func shuffle(nums []int, n int) []int {
ans := make([]int,0, 2 * n)
for i := 0; i < n; i++ {
ans = append(ans, nums[i])
ans = append(ans, nums[n+i])
}
return ans
}
// 写法三
func shuffle(nums []int, n int) []int {
ans := make([]int, 2 * n)
for i, num := range nums[:n] {
ans[2*i] = num
ans[2*i+1] = nums[n+i]
}
return ans
}
原地模拟
数据范围:1 <= nums[i] <= 10^3
func shuffle(nums []int, n int) []int {
var left, right = 1, n
for i := 1; i < 2*n-1; i++ {
if i%2 == 1 {
nums[i] = nums[right]&0x3FF<<10 | nums[i]
right++
} else {
nums[i] = nums[left]&0x3FF<<10 | nums[i]
left++
}
}
for i := 1; i < 2*n-1; i++ {
nums[i] >>= 10
}
return nums
}
java
class Solution {
public int[] shuffle(int[] nums, int n) {
int index = 0, mask = (1 << 10) - 1;
for (int i = 0; i < n; i++) {
nums[index++] = (nums[i] & mask) << 10 | (nums[index - 1] & mask);
nums[index++] = (nums[i + n] & mask) << 10 | (nums[index - 1] & mask);
}
for (int i = 0; i < 2*n; i++) nums[i] >>= 10;
return nums;
}
}