LeetCode(Array)1470. Shuffle the Array

叁歲伎倆 2023-09-23 22:55 128阅读 0赞

1.问题

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 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

2. 解题思路

方法1:

1.定义result数组,长度为2n
2.n之前的元素遍历循环插入数组,n之后的元素遍历循环插入数组,rsult的索引遍历循环加1
3.返回reuslt

方法2:

1.定义result数组,长度为2n
2.遍历数组,长度小于n,2i和2i+1是result遍历后的索引,nums[i]和nums[n+i]是对应的值
3.返回result

方法3:

1.定义result数组,长度为2n
2.索引i为0,left索引的0,right的索引为n
3.如果left小于n,nums[left++]和nums[right++]添加到result数组中
4.返回result

3. 代码

代码1:

  1. class Solution {
  2. public int[] shuffle(int[] nums, int n) {
  3. int[] result = new int[2 * n];//1.定义result数组,长度为2n
  4. for (int i = 0, j = n, idx = 0; idx < result.length; i++, j++) {
  5. //2.n之前的元素遍历循环插入数组,n之后的元素遍历循环插入数组,rsult的索引遍历循环加1
  6. result[idx++] = nums[i];
  7. result[idx++] = nums[j];
  8. }
  9. return result;//3.返回reuslt
  10. }
  11. }

以下代码虽然运行没有问题,但时间复杂度较高,不推荐

  1. class Solution {
  2. public int[] shuffle(int[] nums, int n) {
  3. int[] result = new int[nums.length];
  4. int[] x = new int[n];
  5. int[] y = new int[n];
  6. System.arraycopy(nums,0,x,0,n);
  7. System.arraycopy(nums,n,y,0,n);
  8. List list = new ArrayList<Integer>();
  9. for(int i=0;i<n;i++){
  10. list.add(x[i]);
  11. list.add(y[i]);
  12. }
  13. for(int j=0;j<nums.length;j++){
  14. result[j]= (int) list.get(j);
  15. }
  16. return result;
  17. }
  18. }

代码2:

  1. class Solution {
  2. public int[] shuffle(int[] nums, int n) {
  3. int[] result = new int[2*n];//1.定义result数组,长度为2n
  4. for(int i = 0; i < n; i++){
  5. //2.遍历数组,长度小于n,2*i和2*i+1是result遍历后的索引,nums[i]和nums[n+i]是对应的值
  6. result[2 * i] = nums[i];
  7. result[2 * i + 1] = nums[n+i];
  8. }
  9. return result;//3.返回result
  10. }
  11. }

代码3:

  1. class Solution {
  2. public int[] shuffle(int[] nums, int n) {
  3. int [] result = new int[2*n];//1.定义result数组,长度为2n
  4. int i = 0;//索引i为0,left索引的0,right的索引为n
  5. int left = 0;
  6. int right = n;
  7. while(left < n){
  8. //3.如果left小于n,nums[left++]和nums[right++]添加到result数组中
  9. result[i++] = nums[left++];
  10. result[i++] = nums[right++];
  11. }
  12. return result;
  13. }
  14. }

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读