【再学javascript算法之美】前端面试频率比较高的基础算法题

基础算法题练习代码,看看能做出几道题

代码实现

  • 找出字符串中出现次数最多的字符
js 复制代码
const array = "cncnansdnajsadnjasndjnasjdnjj";

// 找出出现次数最多的字符
let obj = {};
for (let index = 0; index < array.length; index++) {
  const element = array[index];
  if (element in obj) {
    obj[element] += 1;
  } else {
    obj[element] = 1;
  }
}
console.log(obj);
  • 搜索一个字符在字符串中出现的次数
js 复制代码
// 搜索一个字符在字符串中出现的次数
function searchStr(str, target) {
  let count = 0;
  let index = 0;
  console.log(str[count]);
  while (index < str.length) {
    if (str[index] === target) {
      count++;
    }
    index++;
  }

  return count;
}

const ret = searchStr(array, "a");
console.log(ret);
  • 搜索一个字符在字符串中出现的次数
js 复制代码
// 搜索一个字符在字符串中出现的次数
// const array = "cncnansdnajsadnjasndjnasjdnjj";

function findDataTimes(str, target) {
  let index = 0;
  let count = 0;
  while (index < str.length) {
    if (str.indexOf(target, index) > -1) {
      index = str.indexOf(target, index) + 1;
      console.log("🚀 ~ findDataTimes ~ index:", index);
      count++;
    } else {
      index++;
    }
  }
  return count;
}
const ret2 = findDataTimes(array, "d");
console.log(ret2);
  • 快速排序算法实现数据的排序

    思路也很简单,取中间值为基准,小的放到左边的数据,大的放到右边的数组,相等于的房一个数组,然后进行递归,最后就得到正确的顺序了

js 复制代码
let data = [11, 2, 3, 4, 23, 45, 6, 10];
// 快速排序实现

function qSort(arr) {
  // 边界情况
  if (arr.length <= 1) return arr;
  if (!Array.isArray(arr)) return arr;

  const pivot = arr[Math.floor(arr.length / 2)]; // 取中间值作为基准点
  const left = [],
    right = [],
    equal = []; // 左右两边数组,相等值单独处理

  for (let num of arr) {
    if (num < pivot) {
      left.push(num);
    } else if (num > pivot) {
      right.push(num);
    } else {
      equal.push(num);
    }
  }
  // 两种写法都可以
  // return qSort(left).concat(equal, qSort(right));
  return [...qSort(left), ...equal, ...qSort(right)];
}

const result = qSort(data);
console.log(result);
相关推荐
ChalesXavier19 分钟前
Fetch API 的基本用法
javascript
是上好佳佳佳呀29 分钟前
【前端(十三)】JavaScript 数组与字符串笔记
前端·javascript·笔记
巴沟旮旯儿29 分钟前
vite项目配置文件和打包
前端·设计模式
彩票管理中心秘书长38 分钟前
Pinia 插件架构与组合式函数:如何让你的 Store 长出“超能力”
前端
彩票管理中心秘书长40 分钟前
Pinia 比 Vuex 强在哪?我用同一个模块写了两种实现,你自己看
前端
yingyima41 分钟前
用 Cron 加 Webhook 打通自动化工作的任督二脉
前端
JackieDYH42 分钟前
CSS Flexbox 与 Grid 的默认行为-布局的底层机制
前端·css·html
彩票管理中心秘书长43 分钟前
E2E测试入门:别让用户帮你点鼠标了,找个机器人替你打工吧
前端
菜蒙爱学习1 小时前
【Markdown】可用的所有 HTML 标准颜色
前端·html
里欧跑得慢1 小时前
CSS 嵌套:编写更优雅的样式代码
前端·css·flutter·web