美文网首页
每日一练---codewars7 Remove Zeros

每日一练---codewars7 Remove Zeros

作者: 即将牛逼的蛋蛋 | 来源:发表于2020-08-12 16:39 被阅读0次

这道题目也是一个4kyu 的难度,难在不准使用数组或者对象的原生方法

[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]
return [7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]

思路

  • 写一个方法,禁止使用数组或者对象的原生方法,
  • 把所有为 0 或者 '0' 的元素,放到数组的最后
  • 那我自己实现一个数组原生的方法代替数组原生的方法
    // Sort "array" so that all elements with the value of zero are moved to the
    // end of the array, while the other elements maintain order.
    // [0, 1, 2, 0, 3] --> [1, 2, 3, 0, 0]
    // Zero elements also maintain order in which they occurred.
    // [0, "0", 1, 2, 3] --> [1, 2, 3, 0, "0"]

    // Do not use any temporary arrays or objects. Additionally, you're not able
    // to use any Array or Object prototype methods such as .shift(), .push(), etc

    // the correctly sorted array should be returned.
    var arrNoZero = [];
    var arrZero = []
    var mypush = function (arr, addArr) {
        for (var i = 0; i < addArr.length; i++) {
            arr[arr.length] = addArr[i]
        }
    };
    for (var i = 0; i < array.length; i++) {
        if (array[i] !== 0 && array[i] !== '0') {
            mypush(arrNoZero, [array[i]]);
        }else {
            mypush(arrZero, [array[i]]);
        }
    }
    array = [...arrNoZero, ...arrZero];
    return array
}

var input = [7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14];

removeZeros(input)

相关文章

网友评论

      本文标题:每日一练---codewars7 Remove Zeros

      本文链接:https://www.haomeiwen.com/subject/vukmdktx.html