奇思妙想小合集

一、将字符串中的大写字母转为小写字母,小写字母转为大写字母

function convertString(str){
    
    
    let newStr = '';
    for (i of str){
    
    
        /[A-Z]/.test(i) ? newStr+=i.toLowerCase() : newStr+=i.toUpperCase();
    }
    return newStr;
}
console.log(convertString('aSa123,./'));  //AsA123,./

二、实现一个字符串匹配算法,从长度为 n 的字符串 S 中,查找字符串 T,若存在返回所在位置

const find = (S, T) => {
    
    
	if (S.length < T.length) return -1;
	for (let i = 0; i < S.length - T.length ; i++) {
    
    
 		if (S.substr(i, T.length) === T) return i ;
	}
	return -1;
};

三、旋转数组

输入: [1, 2, 3, 4, 5, 6, 7] 和 k = 3
输出: [5, 6, 7, 1, 2, 3, 4]
解释:
向右旋转 1 步: [7, 1, 2, 3, 4, 5, 6]
向右旋转 2 步: [6, 7, 1, 2, 3, 4, 5]
向右旋转 3 步: [5, 6, 7, 1, 2, 3, 4]

function rotate(arr, k) {
    
    
  const len = arr.length
  const step = k % len
  return arr.slice(-step).concat(arr.slice(0, len - step))
}
rotate([1, 2, 3, 4, 5, 6], 7)  // [6, 1, 2, 3, 4, 5]

四、算法题「移动零」,给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序

示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

function zeroMove(arr){
    
    
    arr.sort((a,b) => a-b)
    let j = 0;
    for(i of arr){
    
    
        if(i === 0 && j < arr.length){
    
    
            arr.shift();
            arr.push(i);
            j++;
        }
    }
    return arr
}

五、实现 convert 方法,把原始 list 转换成树形结构,要求尽可能降低时间复杂度

// 原始 list 如下
let list =[
    {
    
    id:1,name:'部门A',parentId:0},
    {
    
    id:2,name:'部门B',parentId:0},
    {
    
    id:3,name:'部门C',parentId:1},
    {
    
    id:4,name:'部门D',parentId:1},
    {
    
    id:5,name:'部门E',parentId:2},
    {
    
    id:6,name:'部门F',parentId:3},
    {
    
    id:7,name:'部门G',parentId:2},
    {
    
    id:8,name:'部门H',parentId:4}
];
const result = convert(list, ...);

// 转换后的结果如下
let result = [
    {
    
    
      id: 1,
      name: '部门A',
      parentId: 0,
      children: [
        {
    
    
          id: 3,
          name: '部门C',
          parentId: 1,
          children: [
            {
    
    
              id: 6,
              name: '部门F',
              parentId: 3
            }, {
    
    
              id: 16,
              name: '部门L',
              parentId: 3
            }
          ]
        },
        {
    
    
          id: 4,
          name: '部门D',
          parentId: 1,
          children: [
            {
    
    
              id: 8,
              name: '部门H',
              parentId: 4
            }
          ]
        }
      ]
    },
  ···
];
function convert(list) {
    
    
	const res = []
	const map = list.reduce((res, v) => (res[v.id] = v, res), {
    
    })
	for (const item of list) {
    
    
		if (item.parentId === 0) {
    
    
			res.push(item)
			continue
		}
		if (item.parentId in map) {
    
    
			const parent = map[item.parentId]
			parent.children = parent.children || []
			parent.children.push(item)
		}
	}
	return res
}

猜你喜欢

转载自blog.csdn.net/weixin_46683645/article/details/123257070