您的位置:首页 > 其它

leetcode题解-88. Merge Sorted Array

2017-04-12 19:53 351 查看
题目:

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 nums1 and nums2 are m and n respectively.


本题是要将两个排好序的数组进行合并。首先最简单的思路就是将数组2放在数组1后面,然后sort。代码入下:

public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i=0; i<n; i++){
nums1[m+i] = nums2[i];
}
Arrays.sort(nums1);

}


上面这种方法因为要对数组进行重新排序,丢失了两个排序数组的重要信息,所以效率比较低。我们尝试遍历两个数组的每个元素,然后将其插入到数组1中。代码入下:

public static void merge1(int[] nums1, int m, int[] nums2, int n){
int num1=0, num2=0;
while(num1<m && num2<n){
if(nums1[num1] < nums2[num2])
num1++;
else if(nums1[num1] >= nums2[num2]){
insert(nums1, m, num1, nums2[num2]);
num1++;
num2++;
m++;
}
}
while(num2 < n){
nums1[m++] = nums2[num2++];
}
}
public static void insert(int [] nums, int len, int idx, int num){
for(int i=len; i>idx; i--)
nums[i] = nums[i-1];
nums[idx] = num;
}


上面这种方法的缺点是对于数组2中的每个数都要进行一个插入操作,将数组1中该元素之后的所有元素向后移,极其耗时。所以我们相处了下面这种方法,从数组的末尾处开始插入最大值,这样可以避免重复的插入操作,代码入下:

public static void merge2(int[] nums1, int m, int[] nums2, int n){
int num1=m-1, num2=n-1, num=m+n-1;
while(num1>=0 && num2>=0){
if(nums1[num1] > nums2[num2]) {
nums1[num--] = nums1[num1--];
}else {
nums1[num--] = nums2[num2--];
}
}
while (num2>=0)
nums1[num--] = nums2[num2--];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: