JS 经典算法题

1.获取字符串中出现最多的字母

getMost(str) {
    const a = {}
    const b = str.split('')
    for (let i = 0; i < b.length; i++) {
        console.log('让我康康',b[i])
        if (a[b[i]]) {
            a[b[i]]++
        } else {
            a[b[i]] = 1
            //    a['a'] = 2
            //    a['b'] = 2
            //    a['c'] = 2
            //    a['d'] = 2
            //    a['e'] = 7
            //    a['f'] = 2
            //    a['g'] = 2
        }
    }
    console.log('让你康康',a) // a =  {a:2,b:2,c:2,d:2,e:7,f:2,g:2}
    let num = 0;
    let max = '';
    for (let key in a) {
        if (a[key] > num) {
            num = a[key];
            max = key
        }
    }
    console.log(max + ':' + num);
    return max
}

 2.冒泡函数

   bubbleSort(arr) {
             const len = arr.length; //6
             for (let i = 0; i < len; i++) {
                     for (let j = 0; j < len - 1 - i; j++) {
                             if (arr[j] > arr[j+1]) {        //相邻元素两两对比
                                     let temp = arr[j+1];        //元素交换
                                     arr[j+1] = arr[j];
                                     arr[j] = temp;
                                 }
                         }
                 }
             return arr;
         }


  componentDidMount() {
      console.log('让我康康',this.bubbleSort([10,30,100,2,4,3]))  //长度为6
      //    10 30 2  3  4  100 第1轮
      //    10 2  3  4  30 100 第2轮
      //    2  3  4  10 30 100 第3轮
  }

3.

posted @ 2020-03-10 17:26  一路向北√  阅读(471)  评论(0编辑  收藏  举报

web应用开发&研究 -

业精于勤而荒于嬉。

工作,使我快乐。


Font Awesome | Respond.js | Bootstrap中文网