Merge Sorted Array 合并数组并排序

时间:2023-03-09 06:26:55
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 nums1and nums2 are m and n respectively.

 public class Solution {
public void merge(int A[], int m, int B[], int n) { int i=m-1;
int j=n-1;
int k=m+n-1; while(i>=0 && j>=0) {
A[k--] = A[i] > B[j] ? A[i--] : B[j--]; //!wrong!!! after ?, i,j value changed. A[i--] > B[j--] ? A[i] : B[j]
} while(j>=0) {
A[k--] = B[j--];
}
}
}
 public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] newArr = new int[m+n];
int i = 0,j = 0,k = 0;
while(i < m || j< n)
{
int a = i < m ?nums1[i] :Integer.MAX_VALUE;
int b = j < n ?nums2[j] :Integer.MAX_VALUE;
if(a > b)
{
newArr[k++] = b;
j++;
}
else
{
newArr[k++] = a;
i++;
}
}
System.arraycopy(newArr, 0, nums1, 0, newArr.length);
}
}