LeetCode-转置矩阵

376 阅读1分钟

题目描述

解题方法一

var transpose = function(A) {
    let result=[]
    let num = A[0].length
    for(let i =0;i<num;i++){
        result.push([]);
        for(let j=0;j<A.length;j++){
            let itemIndex = result.length-1;
            result[itemIndex].push(A[j][i])
        }
    }
    return result
};

解题方法二

1、什么是伪数组

var obj = {
  obj_0: "obj_0",
};
var arr = ["arr_o"];

arr[1] = "arr_1";
obj[2] = "obj_1";

console.log("arr", arr); // arr [ 'arr_o', 'arr_1' ]
console.log("obj", obj); // obj { '2': 'obj_1', obj_0: 'obj_0' }

console.log(arr[1]); //arr_1 按照索引值1进行查找的
console.log(obj[2]); //obj_1 按照键值‘2’查找的

console.log(arr[0]);  // arr_o
console.log(obj[1]);  // undefined

console.log(arr.length); // 2
console.log(obj.length); // undefined

通过以上代码,得到数组和对象的差别:

  • 数组通过索引查找与存储,对象通过键值查找与存储
  • 数组存在length属性,而对象没有 伪数组:
  • 是一个对象
  • 拥有length属性
  • 所有的属性都是非负整数
  • 伪数组可以使用数组的大部分方法

组常见的伪数组是函数中的arguments对象:

function arg(a){
  console.log(arguments)
}
arg(1,2,3,'333')
//[Arguments] { '0': 1, '1': 2, '2': 3, '3': '333',length:4 }

2、Array.from()

从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

Array.from(arrayLike, mapFn, thisArg)

  • arrayLike

    想要转换成数组的伪数组对象或可迭代对象。

  • mapFn 可选

    如果指定了该参数,新数组中的每个元素会执行该回调函数。第一个参数为操作元素,第二个参数为当前元素索引值

  • thisArg 可选

    可选参数,执行回调函数 mapFnthis 对象。

var obj = {
  0: "aa",
  1: "bb",
  length: 2,
};
Array.from(obj, (x, y) => {
  console.log(x, y);
});
//aa 0 
//bb 1 

3、Array.prototype.map()

创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。

语法:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array  返回值,foreach可以不返回
}[, thisArg])

参数:

  • callback:生成新数组元素的函数,使用三个参数:

    currentValue``callback 数组中正在处理的当前元素。

    index可选callback 数组中正在处理的当前元素的索引。

    array可选map 方法调用的数组。

  • thisArg可选,执行 callback 函数时值被用作this

解题代码:

var transpose = function (A) {
  return Array.from({ length: A[0].length }, (item, index) => {
    return A.map((v) => {
      console.log(v);
      return v[index];
    });
  });
};