Merge two arrays and sort the final one

前端 未结 11 827
情歌与酒
情歌与酒 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:12

    You should do something like insertion sort. As both the arrays are sorted (except -1s), the smallest number in array2 will be placed somewhere between first element and the first -1, 2nd element of array2 will be placed somewhere anywhere after the 1st -1 in array1 and before or at the 2nd -1 in array1 and so on.

    So you have to insert a particular element of array2 in only a segment of array1 and not the whole array. Also each element of array2 have to consider different segment or subarray of array1. So, effective time complexity of this logic will be O(n+m) where n is the length of array1 and m is the length of array2.

提交回复
热议问题