DEV Community

Cover image for 1470. Shuffle the Array(easy)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1470. Shuffle the Array(easy)

Introduction

Image description

Here we have given an and all we have to do is shuffle the array. So the procedure is we have to separate the array in two parts from the middle and n is the middle point and the array is always have event number of index. Now we have to take element from the each array put it in serial. Like we have nums = [2,5,1,3,4,7], n = 3. Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

Examples

Image description

Image description

Steps

  1. take a new array arr having same length of nums
  2. Run for loop, from 0 to n;
  3. Now in even position put, arr[2*i] = nums[i];
  4. In odd position, arr[2*i+i] = nums[n + i];

Java Code1:

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int [] arr = new int[n*2];
        for(int i = 0; i < n; i++){
            arr[2*i] = nums[i];
            arr[2*i + 1] = nums[n + i];
        }
        return arr;
    }
}
Enter fullscreen mode Exit fullscreen mode

Java Code2:

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] ans = new int[2*n];
        int start = 1, end = n, i = 1;
        ans[0] = nums[0];
        while( i < 2*n){
            if( i % 2 != 0) {
                ans[i] = nums[end];
                end++;
            }
            else{
                ans[i] = nums[start];
                start++;
            }
            i++;
        }
        return ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)