Niuke.com Brushing Questions-Combine Two Ordered Arrays

Problem Description

Given two ordered arrays of integers A and B, please merge array B into array A to become an ordered array.
Note: It can be assumed that the A array has enough space to store the elements of the B array, A and B The initial number of elements are A and B, respectively.

Input description:
input two arrays, two lengths

Output description:
sorted array

Example

Example 1

Enter
[1,2,3],3,[4,5,6],3

Output
[1,2,3,4,5,6]

Solutions

analysis

This question uses the sorting method of placing elements from the right side of the A array to avoid the problem of multiple loops.

method

  1. By looping the A/B array, elements are placed from the right side of the A array.

Code

public class Solution {
    
    
    public void merge(int A[], int m, int B[], int n) {
    
    
        int index = A.length - 1;
        int curA = m - 1;
        int curB = n - 1;

		// A/B元素同时包含
        while (curA >= 0 && curB >= 0) {
    
    
            if (A[curA] > B[curB]) {
    
    
                A[index--] = A[curA--];
            } else {
    
    
                A[index--] = B[curB--];
            }
        }
		// 只包含A数组元素
        while (curA >= 0) {
    
    
            A[index--] = A[curA--];
        }
		// 只包含B数组元素
        while (curB >= 0) {
    
    
            A[index--] = B[curB--];
        }
    }
}

If you want to test, you can go directly to the link of Niuke.com to do the test

Combine two ordered arrays-Niuke.com

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/112580643