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 nums1 and nums2 are m and n respectively.
题意:合并两个有序数组,将nums2的元素合并到nums1中,并且假设nums1数组空间是足够的。其中注意函数的参数,m和n,它们是指要合并的每个数组元素的个数,其分别小于等于各自数组长度。
思路:按照归并排序的思路,因为归并排序中给定的是一个数组的两个区间,所以通常情况下会借助O(n)大小的辅助空间。
代码:
public void merge(int[] nums1, int m, int[] nums2, int n) { int pos1=0,pos2=0; int all_count = 0; int[] temp = new int[m]; System.arraycopy(nums1,0,temp,0,m); while(pos1<m&&pos2<n){ if(temp[pos1]<nums2[pos2]){ nums1[all_count] = temp[pos1]; pos1++; all_count++; }else{ nums1[all_count] = nums2[pos2]; pos2++; all_count++; } } while(pos1<m){ nums1[all_count] = temp[pos1]; pos1++; all_count++; } while(pos2<n){ nums1[all_count] = nums2[pos2]; pos2++; all_count++; } }