[LeetCode] 88. Merge Sorted Array Java
题目:
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.
题意及分析:给出一个有序数组nums1和nums2,将nums1的前m个数和nums2的前n个数合并起来添加到数组A中去。第一想法是直接使用一个数组C保存结果,然后将C赋值个A,但是这样用了额外的空间;这里可以从后往前比较,这样就可以复用数组A的空间了,不用使用额外的数组C。
代码:
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int k = m+n-1; int i = m-1,j=n-1; while(i>=0&&j>=0){ if(nums1[i]<nums2[j]){ nums1[k] = nums2[j]; j--; }else{ nums1[k] = nums1[i]; i--; } k--; } while(i>=0){ nums1[k] = nums1[i]; i--; k--; } while(j>=0){ nums1[k] = nums2[j]; j--; k--; } } }