接外包,有相关需求的可以联系我:Telegram | Email

1470. Shuffle the Array

该文章创建(更新)于11/5/2020,请注意文章的时效性!

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

用队列来实现,先把x(n),y(n)分别输入两个队列x,y。最后按次序拼接即可!

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

参照上面的尝试,运行时间还不错,但memory不算太好!

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

这个就是先找到中间位置,然后以此进行计算。要我说可能就是+1比+n运算省内存?

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

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2020/11/05/1470-shuffle-the-array/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



YouTube | B站

微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码

阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
Just My SocksJMS9272283 【注意手动复制去跳转】
域名 | namesiloemperinter(1美元)
币安 币安