FCC编程题之中级算法篇(中)
介绍
接着上次的中级算法题
目录
- 1. Missing letters
- 2. Boo who
- 3. Sorted Union
- 4. Convert HTML Entities
- 5. Spinal Tap Case
- 6. Sum All Odd Fibonacci Numbers
- 7. Sum All Primes
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);
}
本文也发表在了简书上。
FCC编程题之中级算法篇(中)的更多相关文章
- FCC编程题之中级算法篇(下)
介绍 本篇是"FCC编程题之中级算法篇"系列的最后一篇 这期完结后,下期开始写高级算法,每篇一题 目录 1. Smallest Common Multiple 2. Finders ...
- FCC编程题之中级算法篇(上)
介绍 FCC: 全称为freeCodeCamp,是一个非盈利性的.面向全世界的编程练习网站.这次的算法题来源于FCC的中级算法题. FCC中级算法篇共分为(上).(中).(下)三篇.每篇各介绍7道算法 ...
- POJ C程序设计进阶 编程题#2:字符串中次数第2多的字母
编程题#2:字符串中次数第2多的字母 来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩.) 注意: 总时间限制: 1000ms 内存限制: 65536k ...
- 剑指Offer编程题1——二维数组中的查找
剑指Offer编程题1---------------二维数组中的查找 题目描述 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完 ...
- 剑指Offer_编程题之二维数组中的查找
题目描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数.
- java学习之第五章编程题示例(初学篇)
/* Animal.java */ package animal; public abstract class Animal { public abstract void cry(); public ...
- FCC上的javascript算法题之中级篇
FCC中的javascript中级算法题解答 中级算法的题目中用到了很多js的知识点,比如迭代,闭包,以及对json数据的使用等等,现在将自己中级算法的解答思路整理出来供大家参考讨论.欢迎大家提出新的 ...
- Leetcode - 剑指offer 面试题29:数组中出现次数超过一半的数字及其变形(腾讯2015秋招 编程题4)
剑指offer 面试题29:数组中出现次数超过一半的数字 提交网址: http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163 ...
- 基本套接字编程(3) -- select篇
1. I/O复用 我们学习了I/o复用的基本知识,了解到目前支持I/O复用的系统调用有select.pselect.poll.epoll.而epoll技术以其独特的优势被越来越多的应用到各大企业服务器 ...
随机推荐
- sql:String格式转换为时间进行比较
字符串的格式为 yyyy-MM-dd HH:mm:ss str_to_date(a.time, '%Y-%m-%d %k:%i') < str_to_date(b.time, '%Y-%m-%d ...
- 自动化框架的两种断言设计(pytest 版)
自动化测试断言失败时,根据不同业务场景,可能需要立即终止或继续执行.这里以 Appium + pytest 为例. 一. 断言失败立即终止 用途一:用例的预期结果是其他用例的前提条件时,assert ...
- Android自定义日历控件(继承系统控件实现)
Android自定义日历控件(继承系统控件实现) 主要步骤 编写布局 继承LinearLayout设置子控件 设置数据 继承TextView实现有圆圈背景的TextView 添加Attribute 添 ...
- linux系统管理-软件包管理
概述: inux家族中的软件包管理有很多工具. 一种是在debiton系列的linux中,以像ubuntu的apt-get为代表.对于此种方式的管理方式,个人感觉挺简单方便的, 一种是在Fedora和 ...
- codeforces 567 E. President and Roads 【 最短路 桥 】
给出一个有向图,从起点走到终点(必须走最短路),问一条边是否一定会被经过,如果不经过它,可以减小它的多少边权使得经过它(边权不能减少到0) 正反向建图,分别求出起点到每个点的最短距离,终点到每个点的最 ...
- 页面定制CSS代码初探(一):页面变宽 文本自动换行 图片按比缩放
初识博客 初写博客,先在设置里选了个喜欢的模板 第一眼就爱上了呢!那极简的风格,我喜欢!!但是,应用后,却发现... 纳尼!模板上右侧那张漂亮的图片呢?!我的怎么什么都没有.没有图片好难看啊,瞬间无爱 ...
- HDU1166 敌兵布阵 线段树详解
题解: 更新是线段树的单点更新,简单一点. 有50000个阵营,40000查询,用普通数组肯定超时.区间求和和区间查询问题用线段树最好不过了. 先说说什么是线段树. 区间[1,10]用树的方法存起来, ...
- BZOJ 1856 [SCOI2010]生成字符串 (组合数)
题目大意:给你n个1和m个0,你要用这些数字组成一个长度为n+m的串,对于任意一个位置k,要保证前k个数字中1的数量大于等于0的数量,求所有合法的串的数量 答案转化为所有方案数-不合法方案数 所有方案 ...
- Vue中如何在组件内部实现一个双向数据绑定?
假设有一个输入框组件,用户输入时,同步父组件页面中的数据. 具体思路:父组件通过props传值给子组件,子组件通过 $emit 来通知父组件修改相应的props值,具体实现如下: import Vue ...
- 使用hbase遇到的问题
1.在使用hbase的时候 有很多问题,其中一个 使用sqoop import 从mysql 向hbase导入数据,报错:Error: java.lang.RuntimeException: Coul ...