Member-only story
Leetcode 1470: Shuffle the array
2 min readJun 9, 2020
In this Leetcode problem, we try to shuffle the numbers in a array in a particular manner.
Solutions
I am always amazed how simple problems have many interesting solutions!
Solution 1: New array and 3 pointers
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] res = new int[2 * n];
int i = 0;
int j = n;
int curr = 0;
while (i < n) {
res[curr] = nums[i];
curr++;
i++;
res[curr] = nums[j];
curr++;
j++;
}
return res;
}
}
This is short and effective, easy to understand, no problem with that.
Solution 2: In place with replacement while loops
class Solution {
public int[] shuffle(int[] nums, int n) {
// in place
int N = 2 * n;
for (int i = 1; i < N -1; i++) {
nums[i] = -nums[i];
}
int minNeg = 1;
while (minNeg < N) {
if (nums[minNeg] < 0) {
int index = minNeg;
int ret = nums[index];
while(ret < 0) {
int newIndex = computeNew(index, n);
int newRet = nums[newIndex]…