一、题目叙述:
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.
Subscribe to see which companies asked this question.
二、解题思路:
简单题,归并排序的方法。
(1)开辟数组nums3;
(2)使用归并排序的方法
(3)最后将数组nums3中的内容放回到nums1即可。
三、源码:
public class Solution
{
public void merge(int[] nums1, int m, int[] nums2, int n)
{
int[] nums3 = new int[m + n];
int i = 0;
int j = 0;
int k;
for (k = 0; k < m + n && i < m && j < n; k++)
{
if (nums1[i] > nums2[j])
{
nums3[k] = nums2[j];
j++;
}
else
{
nums3[k] = nums1[i];
i++;
}
}
if (i == m)
for (int q = k; q < m + n; q++)
{
nums3[q] = nums2[j];
j ++;
}
else if (j == n)
for (int q = k; q < m + n; q++)
{
nums3[q] = nums1[i];
i ++;
}
for (int q = 0 ; q < m + n; q++)
{
nums1[q] = nums3[q];
System.out.print(nums1[q] );
}
}
public static void main(String args[])
{
// int[] digits = {0};
Solution solution = new Solution();
int[] abc = {1,5,6,8,9,0,0,0};
int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
solution.merge(abc, 5, b, 3);
// System.out.print(solution.trap(abc));
}
}