zoukankan      html  css  js  c++  java
  • LeetCode OJ 88. Merge Sorted Array

    Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

    Note:
    You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.

    【思路】

    我们设置两个指针p1和p2分别指向nums1和nums2,如果nums[p1]<=nums[p2],则p1向后移动,否则的话我们在nums2中找到从p2起所有比nums[p1]小的元素的个数movlen,然后把nums1中p1后(包含p1)的元素向后移动movlen,然后在nums1空出的位置复制nums2中从p2起movlen个元素。p1+=movlen,p2+=movlen。

    如果循环结束后nums2中还有元素没有被遍历到,则把这些元素直接加到nums1中。代码如下:

     1 public class Solution {
     2     public void merge(int[] nums1, int m, int[] nums2, int n) {
     3         if(nums1==null||nums2==null||m+n>nums1.length) return;
     4         
     5         int totalen = m + n;
     6         int p1 = 0;
     7         int p2 = 0;
     8         int movelen = 0;
     9         while(p1 < m && p2 < n){
    10             if(nums1[p1] <= nums2[p2]) p1++;        //nums1指针向后移动
    11             else{
    12                 movelen++;
    13                 for(int i = p2 + 1; i < n; i++){    //找到nums2中所有比nums1[p1]小的元素的个数
    14                     if(nums2[i] < nums1[p1]) movelen++;
    15                     else break;
    16                 }
    17                 for(int j = m - 1; j >= p1; j--){   //nusm1中的元素向后移动
    18                     nums1[j+movelen] = nums1[j];
    19                 }
    20                 for(int k = 0; k<movelen; k++){     //拷贝nums2中的元素
    21                     nums1[p1+k] = nums2[p2 + k];
    22                 }
    23                 p1 = p1 + movelen;
    24                 m = m + movelen;                    //nums1的长度增加
    25                 p2 = p2 + movelen;
    26                 movelen = 0;
    27              }
    28         }
    29         while(p2 < n){                              //如果nums2中还有元素则直接加到nums1的末尾
    30             nums1[m++] = nums2[p2++];
    31         }
    32     }
    33 }
     
  • 相关阅读:
    P1001 A+B Problem
    NOIP2015D1T2 信息传递
    海淀区赛游记。。。。
    P3375 【模板】KMP字符串匹配
    Print Article HDU
    BZOJ-2-4870: [Shoi2017]组合数问题 矩阵优化 DP
    BZOJ-1- 4868: [Shoi2017]期末考试-三分
    #6164. 「美团 CodeM 初赛 Round A」数列互质-莫队
    湖南大学第十四届ACM程序设计新生杯(重现赛)
    Codeforces Round #530 (Div. 2)
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5512836.html
Copyright © 2011-2022 走看看