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 }

 

 
posted @ 2016-05-20 17:16  Black_Knight  阅读(165)  评论(0编辑  收藏  举报