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);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,244评论 0 23
  • 早上边放着喜马拉雅上叶嘉莹诵读的《给孩子的古诗词》,边和米爸简单交流了一下。 之前因为公众号有推荐,米爸给我推荐了...
    Friz阅读 282评论 0 0
  • 这是一篇写给自己的文章,写不出来或是打算放弃时,就拿出来看看。 今天起了四个题目,写了一半再也写不下去了。卡壳一样...
    闲人捷阅读 275评论 0 4
  • 【大楚】的情书 大楚宝贝, 前段时间我们读了个物理故事绘本,故事本身你不感兴趣,却对里面提到的物理变化和化学变...
    浮沉浮沉阅读 118评论 0 0
  • 一起种一棵树吧 种下后一起等 等第一片叶子抽出来 透出新鲜的绿色的光 等枝干慢慢变得硬实 再也不需要我们的呵护 等...
    Dialing阅读 308评论 2 3