Merge two arrays and sort the final one

前端 未结 11 977
情歌与酒
情歌与酒 2021-01-15 17:42

In an interview I was asked the following question. I am given two arrays, both of them are sorted.

BUT

Array 1 will have few -1\'s and Array 2 will have to

11条回答
  •  死守一世寂寞
    2021-01-15 18:13

    Let me re-phrase three most important aspects of the task:

    • Both arrays are sorted and include positive integers (except -1 place-holders in Array1)
    • The -1 is meaningless placeholder (its position in Array1 is random)
    • Array1 length equals output array length

    Pseudo logic:

    • parse both array1 and array2 from the first position to end of array
    • ignore -1 values in array1
    • if array1[current position] <= array2[current position] then write array1[current position] into merged array and move to next position in array1; otherwise apply same for array2

    Code example:

                public static void AMerge()
            {
                int[] array1 = new int[] { 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 };
                int[] array2 = new int[] { 1, 9, 28 };
                int[] arrayMerged = new int[array1.Length];
    
                int array1Index = 0;
                int array2Index = 0;
    
                for (int arrayMergedIndex = 0; arrayMergedIndex < array1.Length; arrayMergedIndex++)
                {
                    while (array1[array1Index] == -1) array1Index++; //ignore -1 placeholders
                    if ((array1Index < array1.Length && array2Index >= array2.Length) 
                        || array1[array1Index] <= array2[array2Index])  //choose which array will provide current merged value
                    {
                        arrayMerged[arrayMergedIndex] = array1[array1Index];
                        array1Index++;
                    }
                    else
                    {
                        arrayMerged[arrayMergedIndex] = array2[array2Index];
                        array2Index++;
                    }
                }
    
                char[] charsToTrim = { ',', ' '};
                string arrayMergedString = "{";
                foreach (int f in arrayMerged) arrayMergedString += f.ToString() + " ";
                arrayMergedString = arrayMergedString.TrimEnd(charsToTrim) + "}";
                Console.WriteLine(arrayMergedString);
                Console.ReadKey();
            }
        }
    

    Note:

    • Optimizing for speed => creating new arrayMerged; optimization for space would require moving array1 elements in the else branch

提交回复
热议问题