lc88 Merge Sorted Array
因为两个array都已经排好序了,每次取两者间较小的放入新array中,当一个array空了,直接把另一个array剩下的全放入新array即可
1 class Solution { 2 public void merge(int[] nums1, int m, int[] nums2, int n) { 3 int[] res = new int[m+n]; 4 int count = 0; 5 int i=0, j=0; 6 while(i < m || j < n){ 7 if(compare(nums1, i, m, nums2, j, n)){ 8 res[count++] = nums1[i++]; 9 }else 10 res[count++] = nums2[j++]; 11 } 12 13 System.arraycopy(res, 0, nums1, 0, m+n); 14 } 15 16 private boolean compare(int[] nums1, int i, int m, int[] nums2, int j, int n){ 17 if(i == m) 18 return false; 19 if(j == n) 20 return true; 21 return nums1[i] < nums2[j] ? true : false; 22 } 23 }