题目: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数组的m+n-1位置开始,从后往前插入元素。
1 package array; 2 3 public class MergeSortedArray { 4 5 public void merge(int[] nums1, int m, int[] nums2, int n) { 6 for (int i = m + n - 1; i >= 0; --i) { 7 if (m > 0 && n > 0) 8 nums1[i] = nums1[m - 1] > nums2[n - 1] ? nums1[m-- - 1] : nums2[n-- - 1]; 9 else if (m > 0)10 nums1[i] = nums1[m-- -1];11 else12 nums1[i] = nums2[n-- -1];13 }14 }15 16 public static void main(String[] args) {17 // TODO Auto-generated method stub18 int[] nums1 = { 1,3,5,7,9,11,13,15,17,19 };19 int[] nums2 = { 2,4,6,8,10 };20 MergeSortedArray m = new MergeSortedArray();21 m.merge(nums1, 5, nums2, 5);22 }23 24 }
新闻热点
疑难解答