Merges two ordered arrays

Nums1 is an ordered array of integers and nums1 is an ordered array of integers. Nums1 is an ordered array of integers.

The number of elements initialized for nums1 and nums2 is m and n, respectively. You can assume that the space size of nums1 is equal to m + n, so that it has enough space to hold elements from nums2.

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: array traversal

At the same time, traverse two arrays, starting from large to small, nums1 array’s largest index bit is maxIndex, record the current value is num1 and num2, the current index is m-1 and n-1, respectively, the traversal process:

  • If num1 is greater than num2, update the nums1 array maxIndex position to num1, then m minus one, maxIndex minus one;
  • If num1 is not greater than num2, update the nums1 array maxIndex position to num2, then n minus one, maxIndex minus one;
  • The condition for the end of traversal is that m and n are not greater than 0, that is, both arrays are traversed.

After the traversal is complete, num1 is the result of the merge.

import java.util.Arrays; public class LeetCode_088 { public static void merge(int[] nums1, int m, int[] nums2, int n) { int maxIndex = m + n - 1; while (m > 0 || n > 0) { int num1 = Integer.MIN_VALUE, num2 = Integer.MIN_VALUE; if (m > 0) { num1 = nums1[m - 1]; } if (n > 0) { num2 = nums2[n - 1]; } if (num1 > num2) { nums1[maxIndex] = num1; m--; } else { nums1[maxIndex] = num2; n--; } maxIndex--; } } public static void main(String[] args) { int[] nums1 = new int[]{1, 2, 3, 0, 0, 0}, nums2 = new int[]{2, 5, 6}; merge(nums1, 3, nums2, 3); Arrays.stream(nums1).forEach(num -> { System.out.print(num + " "); }); }}

【 Daily Message 】
Hope a good mood every day business as usual, trouble forever closed.