关于数组(一)——遍历

leetcode里面,数组是出现频率最高的题目,尤其是easy的题目更明显。我猜啊,数组的逻辑简单,所以可以实现各种各样的问题的算法。而且,js当中,关于数组的库函数好多,也好好用。一直想要好好总结一下,所以才有了一边刷题,一边写学习coding的心得的博客想法。这都归功于数组——那么多好用的、多到我经常记不住的库函数。

今天就写写数组的遍历吧。


map

  1. map(),返回一个新数组,数组中的元素为原始数组元素调用函数处理的后值。 
  2. map()按照原始数组元素顺序依次处理元素。 
  3. map()不会对空数组进行检测 
  4. map()不改变原始数组 

arr.map(function(currentValue,index,arr),thisValue) 
参数说明 
function(currentValue,index,arr) 必须,函数,数组中的每个元素都会执行这个函数函数参数
函数参数 :
currentValue 必须,当前元素值 
index 可选,当前元素的索引值 
arr 可选,当前元素属于的数组对象。


eg:760. Find Anagram Mappings

Given two lists Aand B, and B is an anagram of AB is an anagram of A means B is made by randomizing the order of the elements in A.

We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.

These lists A and B may contain duplicates. If there are multiple answers, output any of them.

For example, given

A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]

 

We should return

[1, 4, 3, 2, 0]

as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.

My Anwser:

/**
* @param {number[]} A
* @param {number[]} B
* @return {number[]}
*/
var anagramMappings = function(A, B) {
var arr = [];
var len = A.length;
A.map(function(x){
for(i = 0; i < len; i++){
if(x === B[i] && arr.indexOf(i) === -1){
arr.push(i);
break;
}
}

});
return arr;

};

 

2018-01-17 22:04:54

posted on 2018-01-17 22:06  sannere  阅读(97)  评论(0)    收藏  举报

导航