Merge two arrays and sort the final one

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

    function merger(a1, a2) {
      var i = 0;
      var j = 0;
    
      while (i < a1.length && j < a2.length) {
        if (a1[i] > a2[j]) {
          // Swap values
          var temp = a2[j];
          a2[j] = a1[i];
          a1[i] = temp;
          i++;
        } else if (a1[i] !== -1 && a1[i] <= a2[j]) {
          i++;
        } else {
          var temp = a2[j];
          a2[j] = a1[i];
          a1[i] = temp;
          i++;
          j++;
        }
      }
    
      return a1;
    }
    
    var arrayOne = [3, 5, -1, 11, 15, -1, 23, 34, -1, 42];
    var arrayTwo = [6, 19, 38];
    
    console.log(merger(arrayOne, arrayTwo))

    With certain pre-conditions (no other numbers with <0, a1 should be smaller than a2 etc - which could all be handled) this should solve the problem in JS.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题