FCC编程题之中级算法篇(中)

介绍

接着上次的中级算法题


目录


1. Missing letters

Find the missing letter in the passed letter range and return it.
If all letters are present in the range, return undefined.
Here are some helpful links:

  • String.prototype.charCodeAt()
  • String.fromCharCode()

charCodeAt()方法返回一个字符的UTF-16

fromCharCode()方法返回给定参数对应的字符串,如有多个参数,就用,隔开。

思路

  • 对比相邻的两字符,判断他们的UTF-16差值是否等于1.

  • 不等于1时,使用fromCarCode()方法返回较小值+1对应的字符串。

function fearNotLetter(str) {
  for (let i = 0, len = str.length; i < len - 1; i++) {
    if (str.charCodeAt(i + 1) - str.charCodeAt(i) !== 1) {
      return String.fromCharCode(str.charCodeAt(i) + 1);
    }
  }
  return undefined;
}

2. Boo who

Check if a value is classified as a boolean primitive. Return true or false.
Boolean primitives are true and false.
Here are some helpful links:

  • Boolean Objects

方法 1

直接用typeof即可

function booWho(bool) {
  return typeof bool === 'boolean';
}

方法 2

Boolean函数返回一个值为true或false的值,可利用这个特性进行判断。

function booWho(bool) {
  return bool === Boolean(bool);
}

3. Sorted Union

Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Check the assertion tests for examples.
Here are some helpful links:

  • Arguments object
  • Array.prototype.reduce()

此题考察字符串去重

思路

  • 利用reduce()方法和concat()方法进行数组的合并。

  • 利用filter()方法和indeof()方法进行去重。

function uniteUnique(arr) {
  let arr1 = Array.prototype.slice.call(arguments);

  arr1 = arr1.reduce((array1, array2) => {
    return array1.concat(array2);
  });

  return arr1.filter((val, index) => {
    return arr1.indexOf(val) === index;
  });
}

4. Convert HTML Entities

Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
Here are some helpful links:

  • RegExp
  • HTML Entities
  • String.prototype.replace()

思路

  • 确定正则表达式,/[&<>"']/g。

  • 利用replace()方法和正则表达式替换掉对应的字符即可。

function convertHTML(str) {
  return str.replace(/[&<>"']/g, (val) => {
    return '&' + {
      '&': 'amp',
      '<': 'lt',
      '>': 'gt',
      '"': 'quot',
      '\'': 'apos'
    }[val] + ';';
  });
}

5. Spinal Tap Case

Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
Here are some helpful links:

  • RegExp
  • String.prototype.replace()

思路

  • 去掉'_',替换成' '(空格)。

  • 在所有大写字母前加入一个空白。

  • 如果开头有空白,把空白去掉。

  • 把大写字母前的一个或多个空白换为'-'。

  • 把大写字母都转为小写。

function spinalCase(str) {
  return str.replace(/_/g, ' ').replace(/([A-Z])/g, ' $1').replace(/^\s/, '').replace(/\s+/g, '-').toLowerCase();
}

6. Sum All Odd Fibonacci Numbers

Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than 10 are 1, 1, 3, and 5.
Here are some helpful links:

  • Remainder

菲波那切数列,从第三位起,每一位数都是前两位数之和。此题求的是和,因此没必要存储数字,直接判断后相加即可。

思路

  • 判断当前的菲波那切数是否为奇数,如果是,则加上

  • 利用ES6的新语法解构赋值,进行简单的数值交换。

function sumFibs(num) {
  let a = 1;
  let b = 1;
  let sum = 0;

  while (a <= num) {
    sum += a % 2 !== 0 ? a : 0;
    [a, b] = [b, a + b];
  }

  return sum;
}

7. Sum All Primes

Sum all the prime numbers up to and including the provided number.
A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two.
The provided number may not be a prime.
Here are some helpful links:

  • For Loops
  • Array.prototype.push()

质数,只能被1和其自身整除。利用各种质数筛选法筛选好质数后相加即可得到答案。

思路

  • 利用某种质数筛选法筛选出质数,并添加到数组里。

  • 利用reduce()方法相加

方法 1

利用除法直接判断。但这种算法重复率高,效率低。

function sumPrimes(num) {
  if (num < 2) {
    return 0;
  }
  let arr = [2];
  let isPrime = 3;

  while (isPrime <= num) {
    // 判断是否是质数
    for (let i = 0, len = arr.length; i < len; i++) {
      if (isPrime % arr[i] === 0) {
        break;
      }
      if (Math.pow(arr[i], 2) > isPrime) {
        arr.push(isPrime);
        break;
      }
    }
    isPrime++;
  }

  return arr.reduce((sum, val) => {
    return sum + val;
  });
}

方法 2

利用埃拉托斯特里筛法进行筛选。

ceil()方法对一个浮点数向上取整。

function sumPrimes(num) {
  let arr = [];

  for (let i = 0; i <= num; i++) {
    arr.push(i);
  }

  for (let i = 2, len = Math.ceil(Math.sqrt(num)); i < len; i++) {
    if (!!arr[i]) {
      for (let j = i * 2; j <= num; j += i) {
        arr[j] = undefined;
      }
    }
  }
  arr.splice(0, 2);

  return arr.filter((val) => {
    return !!val;
  }).reduce((sum, val) => {
    return sum + val;
  }, 0);
}

本文也发表在了简书上。

转载于:https://www.cnblogs.com/laoho/p/7650614.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值