The sword refers to Offer - merged array

Title description: There are two sorted arrays A1 and A2, and there is enough free space at the end of A1 to accommodate A2. Please implement a function that inserts all numbers in A2 into A1, and all numbers are sorted.

Analysis: Because the two arrays have been sorted, there is enough space at the end of the cut A1, then we will solve it from the perspective of the end. Start the comparison from the end of A1 and A2, put the larger at the end of A1's capacity, and scan forward. Because it is written in c#, I redeclare an array to store the values ​​of A1 and A2.

code show as below:

private static int[] CombineSortArray(int[] A1,int[] A2)
        {
            if (A1 == null || A2 == null)
                return new int[] { 0 };
            int a1Len = A1.Length;
            int a2Len = A2.Length;
            int newLen = a1Len + a2Len;
            int[] result = new int[newLen];
            for(int i=a1Len-1,j=a2Len-1;i>=0 || j>=0;)
            {
                //Determine whether A1 and A2 are finished
                if(i<0)
                {
                    result[newLen - 1] = A2[j];
                    j--;
                    newLen--;
                    continue;
                }
                if (j < 0)
                {
                    result[newLen - 1] = A1[i];
                    i--;
                    newLen--;
                    continue;
                }

                if (A1[i]>A2[j])
                {
                    result[newLen - 1] = A1[i];
                    i--;
                }
                else
                {
                    result[newLen - 1] = A2[j];
                    j--;
                }
                newLen--;
            }
            return result;
        }
Summary: not elegant enough to write, too much judgment.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326659440&siteId=291194637
Recommended