文章目录[隐藏]
1470. Shuffle the Array
- Easy
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
- 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
Way
Python
- my way
用队列来实现,先把x(n),y(n)分别输入两个队列x,y。最后按次序拼接即可!
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
x = []
y = []
m = 0
while(m <= 2*n - 1):
if(m <= n - 1):
x.append(nums[m])
else:
y.append(nums[m])
m += 1
ret = []
i = 0
while(i <= n - 1):
ret.append(x[i])
ret.append(y[i])
i += 1
return ret
- best way in leetcode
这一个就是把我上面存放然后取队列的过程给优化了!
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
ans = []
for x in range(n):
ans.append(nums[x])
ans.append(nums[x+n])
return ans
JAVA
- my way
参照上面的尝试,运行时间还不错,但memory不算太好!
class Solution {
public int[] shuffle(int[] nums, int n) {
int [] ret = new int[2*n];
int m = 0;
while (m <= n-1){
ret[2*m] = nums[m];
ret[2*m+1] = nums[m + n];
m += 1;
}
return ret;
}
}
- the way in leetcode
这个就是先找到中间位置,然后以此进行计算。要我说可能就是+1比+n运算省内存?
class Solution {
public int[] shuffle(int[] nums, int n) {
//Base case:if nums is null or length 0, or n<2
if(nums==null || nums.length==0 || n<2)
return nums;
int size=nums.length;
//array to store solution
int[] soln = new int[size];
soln[0]=nums[0];
//2 pointers to iterate throuh nums[]
int mid=size/2;
int x=1;
int y=mid;
int index=1;
//iterate through nums[]
while(true)
{
soln[index++] = nums[y++];
if(index==size)
break;
soln[index++] = nums[x++];
}
return soln;
}
}