Merge two arrays and sort the final one

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

    You can try following approach:

    Logic

    • Create a new array that will be returned.
    • Check for first element in arrayTwo and keep it in a variable say val.
    • Loop over arrayOne and check if current value is greater than val, push it in array and decrement value of i by 1 to check next value as well with current element.
    • Now check for current element. If it is less than 0, ignore it, else push value to array.
    • Return this array.

    function mergeAndSort(a1, a2) {
      var matchCount = 0;
      var ret = [];
    
      for (var i = 0; i < a1.length; i++) {
        var val = a2[matchCount];
        if (a1[i] > val) {
          ret.push(val)
          matchCount++
          i--;
          continue;
        }
        if (a1[i] > 0) {
          ret.push(a1[i]);
        }
      }
      console.log(ret.join())
      return ret;
    }
    
    
    var arrayOne = [3, 6, -1, 11, 15, -1, 23, 34, -1, 42]
    var arrayTwo = [7, 19, 38];
    var arrayThree = [1, 9, 28];
    var arrayFour = [1,2,5]
    
    mergeAndSort(arrayOne, arrayTwo)
    mergeAndSort(arrayOne, arrayThree)
    mergeAndSort(arrayOne, arrayFour)
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }

    Note: Not putting check for number of elements in arrayTwo as its clearly mentioned in question that it will be same.

提交回复
热议问题