LeetCode (1470) - rearrange the array

Article Directory

topic

1470. Rearrange the array
Here is an array nums, with 2n elements in the array, arranged in the format [x1,x2,...,xn,y1,y2,...,yn].
Please rearrange the array in the format [x1,y1,x2,y2,…,xn,yn] and return the rearranged array.

Example 1:

输入:nums = [2,5,1,3,4,7], n = 3
输出:[2,3,5,4,1,7] 
解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7]

Example 2:

输入:nums = [1,2,3,4,4,3,2,1], n = 4
输出:[1,4,2,3,3,2,4,1]

Example 3:

输入:nums = [1,1,2,2], n = 2
输出:[1,2,1,2]

prompt:

1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3]

Problem solution (Java)

class Solution 
{
    
    
    public int[] shuffle(int[] nums, int n) 
    {
    
    
        int[] result = new int[2*n];
        int first = 0;
        int second = n;
        //填充偶数索引
        for(int index = 0;index < 2*n;index+=2)
        {
    
    
            result[index] = nums[first++];
        }
        //填充奇数索引
        for(int index = 1;index < 2*n;index+=2)
        {
    
    
            result[index] = nums[second++];
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/113955515
Recommended