1470. Shuffle the Array

# 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

``````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

``````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

``````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;

}
}
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2020/11/05/1470-shuffle-the-array/``

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安