Leetcode 1470. Shuffle the Array
You are given an array nums consisting of 2n elements in the form [x1, x2, ..., xn, y1, y2, ..., yn].
You need to return the array in the form [x1, y1, x2, y2, ..., xn, yn].
Example:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
The elements in the nums array should be rearranged such that elements from x and y are interleaved.
n being zero?nums has exactly 2n elements. If n is provided but not properly constrained, checks could be added.2n.Let’s implement the solution in Java:
public class Solution {
public int[] shuffle(int[] nums, int n) {
int[] result = new int[2 * n];
int j = 0;
for (int i = 0; i < n; i++) {
result[j++] = nums[i];
result[j++] = nums[i + n];
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {2,5,1,3,4,7};
int n = 3;
int[] shuffled = sol.shuffle(nums, n);
for (int num : shuffled) {
System.out.print(num + " ");
}
}
}
The time complexity for this solution is:
result of length 2n to store the shuffled elements.i from 0 to n-1, we place the ith element from the first half of nums and the ith element from the second half of nums alternately into result.result is returned which has elements in the required shuffled order.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?