88. Merge Sorted Array

Easy

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]
package leetcode.easy;

public class MergeSortedArray {
	@org.junit.Test
	public void test() {
		int[] nums1 = { 1, 2, 3, 0, 0, 0 };
		int m = 3;
		int[] nums2 = { 2, 5, 6 };
		int n = 3;
		print(nums1);
		print(nums2);
		merge(nums1, m, nums2, n);
		print(nums1);
	}

	public void merge(int[] nums1, int m, int[] nums2, int n) {
		for (int i = m, j = 0; i < nums1.length && j < nums2.length; i++, j++) {
			nums1[i] = nums2[j];
		}
		sort(nums1, m + n);
	}

	private static void sort(int[] nums, int m) {
		for (int i = 0; i < m - 1; i++) {
			for (int j = 0; j < m - 1 - i; j++) {
				if (nums[j] > nums[j + 1]) {
					int temp = nums[j];
					nums[j] = nums[j + 1];
					nums[j + 1] = temp;
				}
			}
		}
	}

	private static void print(int[] nums) {
		for (int i = 0; i < nums.length; i++) {
			System.out.print(nums[i] + " ");
		}
		System.out.println();
	}
}
01-14 07:08