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()方法返回給定參數(shù)對應(yīng)的字符串,如有多個參數(shù),就用,隔開。

思路

  • 對比相鄰的兩字符,判斷他們的UTF-16差值是否等于1.

  • 不等于1時,使用fromCarCode()方法返回較小值+1對應(yīng)的字符串。

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函數(shù)返回一個值為true或false的值,可利用這個特性進(jìn)行判斷。

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()方法進(jìn)行數(shù)組的合并。

  • 利用filter()方法和indeof()方法進(jìn)行去重。

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()

思路

  • 確定正則表達(dá)式,/[&<>"']/g。

  • 利用replace()方法和正則表達(dá)式替換掉對應(yīng)的字符即可。

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()

思路

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

  • 在所有大寫字母前加入一個空白。

  • 如果開頭有空白,把空白去掉。

  • 把大寫字母前的一個或多個空白換為'-'。

  • 把大寫字母都轉(zhuǎn)為小寫。

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

菲波那切數(shù)列,從第三位起,每一位數(shù)都是前兩位數(shù)之和。此題求的是和,因此沒必要存儲數(shù)字,直接判斷后相加即可。

思路

  • 判斷當(dāng)前的菲波那切數(shù)是否為奇數(shù),如果是,則加上

  • 利用ES6的新語法解構(gòu)賦值,進(jìn)行簡單的數(shù)值交換。

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()

質(zhì)數(shù),只能被1和其自身整除。利用各種質(zhì)數(shù)篩選法篩選好質(zhì)數(shù)后相加即可得到答案。

思路

  • 利用某種質(zhì)數(shù)篩選法篩選出質(zhì)數(shù),并添加到數(shù)組里。

  • 利用reduce()方法相加

方法 1

利用除法直接判斷。但這種算法重復(fù)率高,效率低。

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

  while (isPrime <= num) {
    // 判斷是否是質(zhì)數(shù)
    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

利用埃拉托斯特里篩法進(jìn)行篩選。

ceil()方法對一個浮點數(shù)向上取整。

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);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,891評論 0 23
  • 早上邊放著喜馬拉雅上葉嘉瑩誦讀的《給孩子的古詩詞》,邊和米爸簡單交流了一下。 之前因為公眾號有推薦,米爸給我推薦了...
    Friz閱讀 294評論 0 0
  • 這是一篇寫給自己的文章,寫不出來或是打算放棄時,就拿出來看看。 今天起了四個題目,寫了一半再也寫不下去了。卡殼一樣...
    閑人捷閱讀 305評論 0 4
  • 【大楚】的情書 大楚寶貝, 前段時間我們讀了個物理故事繪本,故事本身你不感興趣,卻對里面提到的物理變化和化學(xué)變...
    浮沉浮沉閱讀 132評論 0 0
  • 一起種一棵樹吧 種下后一起等 等第一片葉子抽出來 透出新鮮的綠色的光 等枝干慢慢變得硬實 再也不需要我們的呵護(hù) 等...
    Dialing閱讀 319評論 2 3