前端算法面试题附加答案

统计一个字符串出现频率最高的字母

	const str = 'gongnengceshizifuchuan';
	const findMaxChart = (string)=> {
        let arr = [...string],
            totalObj = {},
            max = 0,
            maxChart = '';
        arr.forEach(value => {
            if(totalObj[value]){
                totalObj[value]++;
            }else {
                totalObj[value] = 1;
            }
            if(totalObj[value] > max){
                maxChart = value;
                max = totalObj[value]
            }
        })
        return maxChart;
     }
     console.log(findMaxChart(str)); //n

数组去重

	// 1
	const removeDup = (arr) => {
		return arr.filter((item, index, self)=> {
			return self.indexOf(item) === index
		})
	}
	// 2
	const removeDup = (arr) => {
		return [... new Set(arr)]
	}

斐波那契

	const fibonacci = (n) => {
	    let ori = [0 ,1]
	    if(n < 2) {
	        return ori[n]
	    }
	    let one = 1,two =1,sum = 1;
	    for(let i = 2; i < n; i++){
	        sum = one + two;
            one = two;
            two = sum;
	    }
	    return sum;
	}

插入排序

// 插入排序 === 以当前元素与前一个比较,向前移动到合适的位置
	const insertionSort = (arr = []) => {
	    for (let i in arr) {
	        while (i > 0 && arr[i] < arr[i - 1]) {
	            [arr[i], arr[i - 1]] = [arr[i - 1], arr[i]];
	            i--;
	        }
	    }
	    return arr;
	};
	console.log(insertionSort([1, 3, 2, 4, 9, 7, 6])); // [1, 2, 3, 4, 6, 7, 9]

你可能感兴趣的:(前端算法面试,前端,javascript,算法,数据结构,排序算法)