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足够大,所以从nums1末尾开始存数。比较大小的时候要注意边界条件。刚开始用nums1来定边界条件发现很麻烦,转而用nums2,需要考虑的条件少了很多。if condition的前后转化要多注意。
public class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { if(n==0) { return; } int l1=m-1; int l2=n-1; int total=m+n-1; for(int i=total;i>=0;i--) { if(l2>=0&&l1>=0&&nums1[l1]<=nums2[l2]||l1<0) { nums1[i]=nums2[l2]; l2--; } else { nums1[i]=nums1[l1]; l1--; } } } }
时间: 2024-11-06 02:45:36