js算法题
1.Remove String Spaces
1 | function noSpace(x){ |
2.Sort array by string length
1 | function sortByLength (array) { |
3.Handle String
result:1
2
3
4accum("abcd"); // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt"); // "C-Ww-Aaa-Tttt"
`
1 | function accum(s) { |
better:1
2
3
4
5
6function accum(s) {
return s.split('').map((x,index) => x.toUpperCase()+Array(index+1).join(x.toLowerCase())).join('-');
}
function accum(s) {
return s.split('').map((c, i) => (c.toUpperCase() + c.toLowerCase().repeat(i))).join('-');
}
4.Handle Arr
result:1
2
3
4
5
6["az", "toto", "picaro", "zone", "kiwi"] -->
[["az", "toto picaro zone kiwi"],
["az toto", "picaro zone kiwi"],
["az toto picaro", "zone kiwi"],
["az toto picaro zone", "kiwi"]]
`
1 | function partlist(arr) { |
better1
var partlist=a=>a.map((v,i)=>[a.slice(0,i).join(' '),a.slice(i).join(' ')]).slice(1)
5.Get the Middle Character
result:1
2
3
4
5
6
7runBF("test\0") should return "es"
runBF("testing\0") should return "t"
runBF("middle\0") should return "dd"
runBF("A\0") should return "A"
1 | function getMiddle(s) |
better:1
2
3
4function getMiddle(s)
{
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
6.Vowel Count
result:1
2getCount('aeiou'); //5 a,e,i,o,u
getCount('abcde'); //2 a,e
1 | function getCount(str) { |
better:1
2
3function getCount(str) {
return (str.match(/[aeiou]/ig)||[]).length;
}
7.Highest and Lowest
result:1
2
3highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
1 | function highAndLow(numbers){ |
better:1
2
3
4function highAndLow(numbers){
numbers = numbers.split(' ');
return `${Math.max(...numbers)} ${Math.min(...numbers)}`;
}
8.Array Diff
result:1
2
3//It should remove all values from list a, which are present in list b.
array_diff([1,2],[1]) //return [2]
array_diff([1,2,2,2,3],[2]) //return [1,3]
1 | function array_diff(a, b) { |
other:1
2
3
4//includes判断数组是否有某元素
function array_diff(a, b) {
return a.filter(e => !b.includes(e));
}
9.Find the odd int
result:1
2
3findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) //return 5
findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]); //return -1
findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]); //return 5
1 | function findOdd(A) { |
better1
2//异或位运算符,看不懂
const findOdd = (xs) => xs.reduce((a, b) => a ^ b);
10.Persistent Bugger.
result:1
2
3
4
5
6
7
8//which is the number of times you must multiply the digits in num until you reach a single digit.
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4 count:3
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126, count:4
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number count:0
1 | function persistence(num) { |
better:1
2
3
4
5const persistence = num => {
return `${num}`.length > 1
? 1 + persistence(`${num}`.split('').reduce((a, b) => a * +b))
: 0;
}
11.The Supermarket Queue
函数有两个输入变量:
客户:表示队列的正整数数组。每个整数表示一个客户,其值是它们需要检查的时间量。
N:一个正整数,结账柜台的数量。
函数应该返回一个整数,所需的总时间。
result:1
2
3
4
5
6
7
8
9
10
11queueTime([5,3,4], 1)
// should return 12
// because when n=1, the total time is just the sum of the times
queueTime([10,2,3,3], 2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
queueTime([2,3,10], 2)
// should return 12
1 | function queueTime(customers, n) { |
better1
2
3
4
5
6
7
8
9//不需要截第一个数组,不需要排序,直接对最小的值加
function queueTime(customers, n) {
var w = new Array(n).fill(0);
for (let t of customers) {
let idx = w.indexOf(Math.min(...w));
w[idx] += t;
}
return Math.max(...w);
}
12.toWeirdCase
result: 大写小写大写小写1
2
3//even upper/ odd lower
toWeirdCase( "String" );//=> returns "StRiNg"
toWeirdCase( "Weird string case" );//=> returns "WeIrD StRiNg CaSe"
1 | function toWeirdCase(string){ |
better:1
2
3
4//每匹配两个字母
function toWeirdCase(string){
return string.replace(/(\w{1,2})/g,(m)=>m[0].toUpperCase()+m.slice(1))
}
13.Handle Time
result1
2
3humanReadable(60) //rerurn '00:01:00',
humanReadable(86399) //return '23:59:59'
humanReadable(359999) //return '99:59:59'
1 | function humanReadable(seconds) { |
1 | //傻了,不用判断时间 |
14.Split Strings
result:1
2solution('abc') // should return ['ab', 'c_']
solution('abcdef') // should return ['ab', 'cd', 'ef']
1 | //偶数次会导致末尾多个空,直接用match更好 |
better:1
2
3function solution(str){
return (str + "_").match(/../g);
}
15.Arrays of cats and dogs
result: Dog在n个节点内抓到Cat,return被抓的C1
2
3
4//solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4.
//solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4.
//solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1.
//solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught!
1 | function solve(arr,n){ |
16.Dont drive too long!
result: Drive的时间<9小时
9小时>1
2
3
4
5
6
7var dailyShedule = [ ["7:00-10:30","Drive"],
["10:30-10:45","Rest"],
["10:45-11:45","Drive"],
["11:45-12:15","Rest"],
["12:15-16:45","Drive"],
["16:45-20:15","Work"]];
//-> should return false,9 hours of driving in total.
1 | function shouldIBeTired(dailyShedule){ |
17.Array plus array
result:1
//arrayPlusArray([1, 2, 3], [4, 5, 6]), 21
1 | function arrayPlusArray(arr1, arr2) { |
better:1
2
3
4
5
6
7function arrayPlusArray(arr1, arr2) {
return arr1.concat(arr2).reduce((acc, cur) => acc + cur);
}
function arrayPlusArray(...arrays) {
return [].concat(...arrays).reduce((a,b) => a+b,0)
}
18.order Array
result:1
2
3//"56 65 74 100 99 68 86 180 90"
//ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99"
// 100->1+0+0 =1 56/65 -> '56'<'65'
1 | function orderWeight(string) { |
19.Magic Squares
result:
判断是否是数独1
2
3
4
5var arr = [
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
]; //return true
思路:把所有情况组成个新数组1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32function magicSquare(arr){
if(arr.length == 0 || arr[0] == null) return false;
let newArr = [...arr],
flag = true,
len = arr.length,
sum = arr[0].reduce((a,b)=>a+b);
arr[0].map((i,n)=>{
let item = [];
if(n == 0){ //X
let item2 = []
for(let j = 0; j<len; j++){
item2.push(arr[j][j])
}
newArr.push(item2)
}
if(n == len){ //X
let item3 = []
for(let j = 0; j<len; j++){
item3.push(arr[j][n-j])
}
newArr.push(item3)
}
for(let j = 0; j<len; j++){ // |||
item.push(arr[j][n])
}
newArr.push(item)
})
newArr.map(k=>{
flag = flag && sum == k.reduce((a,b)=>a+b)
})
return flag
}
20.Sum of array singles
result:1
2//repeats([4,5,7,5,4,8]) = 15
// because only the numbers 7 and 8 occur once, and their sum is 15.
1 | function repeats(arr){ |
better:1
2
3
4//filter 索引不变代表唯一,达到筛选效果
function repeats(arr){
return arr.filter(v => arr.indexOf(v) === arr.lastIndexOf(v)).reduce((a,b) => a + b, 0);
}
21.Sentence Calculator
result:
Lower case [a-z]: ‘a’=1, ‘b’=2, ‘c’=3, …, ‘z’=26
Upper case [A-Z]: ‘A’=2, ‘B’=4, ‘C’=6, …, ‘Z’=52
Digits [0-9] their numeric value: ‘0’=0, ‘1’=1, ‘2’=2, …, ‘9’=9
Other characters: 0 value
//lettersToNumbers(“I Love You”), 1701
2
3
4
5
6
7
8
9
10
11
12
13
14function lettersToNumbers(s) {
let sum = 0;
s.split('').map(i=>{
let num = i.charCodeAt();
if(num>64 && num<91){
sum += (num-64)*2
} else if( num>96 && num<123){
sum += num-96
} else if( num>47 && num< 58 ) {
sum += +i
}
})
return sum
}
better:1
2
3
4
5
6
7function lettersToNumbers(s) {
let key = c =>
/[a-z]/.test(c) ? c.charCodeAt() - 96 :
/[A-Z]/.test(c) ? (c.charCodeAt() - 64) * 2 :
/\d/.test(c) ? +c : 0
return [...s].reduce((s, v) => s + key(v), 0)
}
22.Follow that Spy
首位相连
Example:
routes = [[USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN]]
result: “USA, BRA, UAE, JPN, PHL”1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30// it should return the places from the given routes
function findRoutes(routes) {
//Your code here...
let result = [],
last = '';
(function eachRoutes(){
let arr = [];
flag = true;
routes.map(item => {
if(result.length === 0){//find first
routes.map(i => {
arr.push(i[0], i[1])
})
let noRepeat = arr.filter(j => arr.indexOf(j) === arr.lastIndexOf(j));
result = routes.filter(n => noRepeat.includes(n[0]))[0];
last = routes.filter(n => noRepeat.includes(n[1]))[0];
} else {
if(result[result.length-1] === last[1]){
flag = false;
}
if(item[0] === result[result.length-1]){
result.push(item[1])
}
}
})
if(!flag) return;
eachRoutes()
})()
return result.join(', ')
}
23.Convert string to camel case
result:
toCamelCase(“the-stealth-warrior”) // returns “theStealthWarrior”
toCamelCase(“The_Stealth_Warrior”) // returns “TheStealthWarrior”
1 | function toCamelCase(str){ |
better:1
2
3function toCamelCase(str){
return str.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
}
24.回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
result:
121,11,1221 –> true
123 –> false1
2
3
4var isPalindrome = function(x) {
let arr = String(x).split('');
return String(x).substr(0,parseInt(arr.length/2)) === arr.splice(Math.ceil(arr.length/2)).reverse().join('').toString()
};
25.删除排序数组中的重复项
result:
[0,0,1,1,1,2,2,3,3,4] –> 原数组被修改为 0, 1, 2, 3, 4
1 | var removeDuplicates = function(nums) { |