前端常见算法题

1. ['1', '2', '3'].map( parseInt );     //知识点:map和parseInt的使用

  map支持两个参数: 1.回调函数callback  2.用于回调函数中this的值(如果不传默认是undefine).   其回调函数默认接受三个参数(val, index, arr),即(当前遍历的value, 当前遍历的索引值, 当前遍历的数组)。

  parseInt函数支持两个参数,1.要解析的字符串,  2. 要解析的数字的基数,该值介于 2 ~ 36 之间。

如果省略该参数或其值为 0,则数字将以 10 为基础来解析。如果它以 “0x” 或 “0X” 开头,将以 16 为基数。

如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN。

所以,遍历的过程实际上是: 

//step1: parseInt(1, 0)    1
//step2: parseInt(2, 1) NaN(第二个参数小于2)
//step3: parseInt(3, 2) NaN(第二个参数是二进制,但是二进制不能解析‘3’,所以是NaN)

2.统计一段字符串中每个字符出现的次数 ?   //知识点: map(), 对象的合理使用

参考代码:

   let str = 'xiaoqingxulala';
    let strTimes = {};
    str.split('').map(function (p1, p2, p3) {
        if(!strTimes[p1]) {
            result[p1] = 1;
        }else {
            strTimes[p1] += 1;
        }
    });
    console.log(strTimes)

升级版: 找出一段字符串中出现次数最多的字符和次数?  //知识点:for...in...

参考代码:

   //上面已经统计出每个字符出现的次数的对象strTimes:{x: 2, i: 2, a: 3, o: 1, q: 1, …}
   let maxNum = 0; let maxStr = ''; for(let i in strTimes) { if(strTimes[i] > maxNum){ maxNum = strTimes[i]; maxStr = i; } } console.log(maxStr+':'+maxNum)

弄懂思路以后,转为高级一点的写法就是:

const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';
const res = str.split('').reduce((accumulator, cur) => {accumulator[cur] ? accumulator[cur]++ : accumulator[cur] = 1; return accumulator;}, {});

 

3.对整型数组进行排序.

大家可能首先想到的是数组自带的sort方法,但是事实证明这个是有问题的,如下:

var arr = [2,3,4,2,5,6,8,61];
console.log(arr.sort());      //[2, 2, 3, 4, 5, 6, 61, 8]

为什么结果会不对呢,因为sort方法不是严格按照数值的大小进行排序的,而是根据元素的字符编码,所以会出现上述结果.   so,可以用sort()对字符串数组进行排序,如:

['abc', 'ccd', 'ced','eaa'].sort();

回到原题上来,如何正确实现整型数字的排序,只需要添加一个函数:
var arr = [2,3,4,23,5,6,8,61];

function sortNumber(a, b) {
    return a-b;
}
console.log(arr.sort(sortNumber))

 4. 超大数值(超过MAX_SAFE_INTEGER)相加 

function sumBigNumber(a, b) {
    let res = '',
      temp = 0;
    a = a.toString().split('');
    b = b.toString().split('');
    while (a.length || b.length || temp) {
      temp += parseInt(a.pop()) + parseInt(b.pop());
      res = (temp % 10) + res;
      temp = temp > 9;
    }
    return res.replace(/^0+/, '');
  }

 

posted @ 2017-10-23 09:38  小情绪^_^  阅读(812)  评论(0编辑  收藏  举报