>  기사  >  웹 프론트엔드  >  JavaScript 인터뷰의 일반적인 알고리즘 질문에 대한 자세한 설명

JavaScript 인터뷰의 일반적인 알고리즘 질문에 대한 자세한 설명

黄舟
黄舟원래의
2017-03-02 14:45:111331검색

JavaScript 사양

JavaScript의 승격 변수 설명

소위 승격이란 이름에서 알 수 있듯이 JavaScript가 모든 선언을 맨 위로 승격시키는 것을 의미합니다. 현재 범위의. 즉, 변수가 선언되기 전에 사용할 수 있지만 JavaScript가 선언을 맨 위로 올리더라도 실제 초기화 프로세스는 수행하지 않습니다.

use strict;의 역할을 설명하세요

use strict;이름에서 알 수 있듯이 JavaScript는 소위 엄격 모드에서 실행됩니다. 주요 장점 중 하나는 개발자를 강제할 수 있다는 것입니다. 선언되지 않은 변수를 사용하지 마십시오. 이전 버전의 브라우저나 실행 엔진의 경우 이 명령은 자동으로 무시됩니다.

// Example of strict mode
"use strict";

catchThemAll();
function catchThemAll() {
  x = 3.14; // Error will be thrown
  return x * x;
}

이벤트 버블링이 무엇인지, 어떻게 피할 수 있는지 설명하세요

이벤트 버블링은 이벤트가 현재 요소를 트리거할 뿐만 아니라 중첩된 순서로 상위 요소에 전달된다는 의미입니다. 직관적으로 말하면 하위 요소의 클릭 이벤트는 상위 요소의 클릭 이벤트 핸들러에서도 캡처됩니다. 이벤트 버블링을 방지하려면 IE 9 이하에서는 event.stopPropagation() 또는 event.cancelBubble을 사용할 수 있습니다.

==와 ===

===의 차이점은 소위 엄격한 비교입니다. 주요 차이점은 ===에서 유형과 값을 비교한다는 것입니다. 단지 가치를 비교하는 것이 아니라 동시에.

// Example of comparators
0 == false; // true
0 === false; // false

2 == '2'; // true
2 === '2'; // false

null과 정의되지 않음의 차이점 설명

JavaScript에서 null은 할당할 수 있는 값이고, 변수가 null로 설정되면 값이 없다는 의미입니다. 정의되지 않음은 변수를 선언했지만 아직 값이 할당되지 않았음을 의미합니다.

프로토타입 상속과 고전적 상속의 차이점을 설명하세요

클래스 상속에서는 클래스가 불변입니다. 언어마다 다중 상속을 지원하는 개념이 다릅니다. 인터페이스, 최종 및 추상. 프로토타입 상속은 더 유연하고 프로토타입 자체는 변경 가능하며 객체는 여러 프로토타입에서 상속될 수 있습니다.

배열

정수 배열에서 가장 큰 곱을 갖는 세 개의 숫자를 찾으세요

정수를 포함하는 정렬되지 않은 배열이 주어지면 가장 큰 곱을 갖는 세 개의 숫자를 찾으라는 메시지가 표시됩니다. .

var unsorted_array = [-10, 7, 29, 30, 5, -10, -70];

computeProduct(unsorted_array); // 21000

function sortIntegers(a, b) {
  return a - b;
}

// greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)
function computeProduct(unsorted) {
  var sorted_array = unsorted.sort(sortIntegers),
    product1 = 1,
    product2 = 1,
    array_n_element = sorted_array.length - 1;

  // Get the product of three largest integers in sorted array
  for (var x = array_n_element; x > array_n_element - 3; x--) {
      product1 = product1 * sorted_array[x];
  }
  product2 = sorted_array[0] * sorted_array[1] * sorted_array[array_n_element];

  if (product1 > product2) return product1;

  return product2
};

연속 배열에서 누락된 숫자 찾기

n개의 연속 숫자 중 n – 1을 포함하는 순서가 지정되지 않은 배열이 주어지면 상한과 하한이 알려져 있으며 O(n) 누락된 숫자를 찾는 복잡성.

// The output of the function should be 8
var array_of_integers = [2, 5, 1, 4, 9, 6, 3, 7];
var upper_bound = 9;
var lower_bound = 1;

findMissingNumber(array_of_integers, upper_bound, lower_bound); //8

function findMissingNumber(array_of_integers, upper_bound, lower_bound) {

  // Iterate through array to find the sum of the numbers
  var sum_of_integers = 0;
  for (var i = 0; i < array_of_integers.length; i++) {
    sum_of_integers += array_of_integers[i];
  }

  // 以高斯求和公式计算理论上的数组和
  // Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2];
  // N is the upper bound and M is the lower bound

  upper_limit_sum = (upper_bound * (upper_bound + 1)) / 2;
  lower_limit_sum = (lower_bound * (lower_bound - 1)) / 2;

  theoretical_sum = upper_limit_sum - lower_limit_sum;

  //
  return (theoretical_sum - sum_of_integers)
}

배열 중복 제거

순서가 지정되지 않은 배열이 있는 경우 배열에서 중복된 숫자를 제거하고 중복되지 않은 새 배열을 반환해야 합니다.

// ES6 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];

Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8]

// ES5 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];

uniqueArray(array); // [1, 2, 3, 5, 9, 8]

function uniqueArray(array) {
  var hashmap = {};
  var unique = [];
  for(var i = 0; i < array.length; i++) {
    // If key returns null (unique), it is evaluated as false.
    if(!hashmap.hasOwnProperty([array[i]])) {
      hashmap[array[i]] = 1;
      unique.push(array[i]);
    }
  }
  return unique;
}

배열 요소의 최대 차이 계산

순서가 지정되지 않은 배열이 주어지면 두 요소 간의 최대 차이를 구합니다. 여기서는 차이 계산의 최소 차이가 필요합니다. 요소의 인덱스는 더 큰 요소의 인덱스보다 작아야 합니다. 예를 들어 [7, 8, 4, 9, 9, 15, 3, 1, 10]이 배열의 계산된 값은 15의 첨자가 1보다 작기 때문에 14(15 – 1) 대신 11( 15 – 4)입니다.

var array = [7, 8, 4, 9, 9, 15, 3, 1, 10];
// [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15`
// Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1.

findLargestDifference(array);

function findLargestDifference(array) {

  // 如果数组仅有一个元素,则直接返回 -1

  if (array.length <= 1) return -1;

  // current_min 指向当前的最小值

  var current_min = array[0];
  var current_max_difference = 0;

  // 遍历整个数组以求取当前最大差值,如果发现某个最大差值,则将新的值覆盖 current_max_difference
  // 同时也会追踪当前数组中的最小值,从而保证 `largest value in future` - `smallest value before it`

  for (var i = 1; i < array.length; i++) {
    if (array[i] > current_min && (array[i] - current_min > current_max_difference)) {
      current_max_difference = array[i] - current_min;
    } else if (array[i] <= current_min) {
      current_min = array[i];
    }
  }

  // If negative or 0, there is no largest difference
  if (current_max_difference <= 0) return -1;

  return current_max_difference;
}

배열 요소의 곱

순서가 지정되지 않은 배열이 있는 경우 새 배열 출력을 반환해야 합니다. 여기서 출력[i]는 요소를 제외한 원래 배열의 요소입니다. O(n) 복잡성으로 구현해야 하는 첨자 i Product:

var firstArray = [2, 2, 4, 1];
var secondArray = [0, 0, 0, 2];
var thirdArray = [-2, -2, -3, 2];

productExceptSelf(firstArray); // [8, 8, 4, 16]
productExceptSelf(secondArray); // [0, 0, 0, 0]
productExceptSelf(thirdArray); // [12, 12, 8, -12]

function productExceptSelf(numArray) {
  var product = 1;
  var size = numArray.length;
  var output = [];

  // From first array: [1, 2, 4, 16]
  // The last number in this case is already in the right spot (allows for us)
  // to just multiply by 1 in the next step.
  // This step essentially gets the product to the left of the index at index + 1
  for (var x = 0; x < size; x++) {
      output.push(product);
      product = product * numArray[x];
  }

  // From the back, we multiply the current output element (which represents the product
  // on the left of the index, and multiplies it by the product on the right of the element)
  var product = 1;
  for (var i = size - 1; i > -1; i--) {
      output[i] = output[i] * product;
      product = product * numArray[i];
  }

  return output;
}

배열 교집합

두 개의 배열이 주어지면 두 배열의 교집합을 찾아야 합니다. 교차점의 요소는 유일한 것이어야 합니다.

var firstArray = [2, 2, 4, 1];
var secondArray = [1, 2, 0, 2];

intersection(firstArray, secondArray); // [2, 1]

function intersection(firstArray, secondArray) {
  // The logic here is to create a hashmap with the elements of the firstArray as the keys.
  // After that, you can use the hashmap&#39;s O(1) look up time to check if the element exists in the hash
  // If it does exist, add that element to the new array.

  var hashmap = {};
  var intersectionArray = [];

  firstArray.forEach(function(element) {
    hashmap[element] = 1;
  });

  // Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added
  secondArray.forEach(function(element) {
    if (hashmap[element] === 1) {
      intersectionArray.push(element);
      hashmap[element]++;
    }
  });

  return intersectionArray;

  // Time complexity O(n), Space complexity O(n)
}

String

문자열 반전

문자열이 주어지면 "Welcome to this Javascript Guide!"와 같이 해당 문자열에 포함된 단어를 반전시킨 후 출력해야 합니다. should 출력은 "emocleW ot siht tpircsavaJ !ediuG"입니다.

var string = "Welcome to this Javascript Guide!";

// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");

// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator);
}

같은 문자로 섞인 문자열

두 개의 문자열이 주어지면 문자가 반대인지 확인하세요. 예를 들어 MaryArmy는 같은 문자이지만 순서가 반대입니다.

var firstWord = "Mary";
var secondWord = "Army";

isAnagram(firstWord, secondWord); // true

function isAnagram(first, second) {
  // For case insensitivity, change both words to lowercase.
  var a = first.toLowerCase();
  var b = second.toLowerCase();

  // Sort the strings, and join the resulting array to a string. Compare the results
  a = a.split("").sort().join("");
  b = b.split("").sort().join("");

  return a === b;
}

문자열에 질문하여 문자열이 회문 문자열인지 확인합니다. 예를 들어 racecarrace car는 모두 회문 문자열입니다.

isPalindrome("racecar"); // true
isPalindrome("race Car"); // true

function isPalindrome(word) {
  // Replace all non-letter chars with "" and change to lowercase
  var lettersOnly = word.toLowerCase().replace(/\s/g, "");

  // Compare the string with the reversed version of the string
  return lettersOnly === lettersOnly.split("").reverse().join("");
}

스택 및 대기열

두 개의 스택을 사용하여 대기열에 넣기 및 대기열에서 빼기 구현

var inputStack = []; // First stack
var outputStack = []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

중괄호가 닫혀 있는지 확인

주어진 표현식이 있는지 확인하는 함수 만들기 중괄호가 닫혀 있는지 여부 닫힘:

var expression = "{{}}{}{}"
var expressionFalse = "{}{{}";

isBalanced(expression); // true
isBalanced(expressionFalse); // false
isBalanced(""); // true

function isBalanced(expression) {
  var checkString = expression;
  var stack = [];

  // If empty, parentheses are technically balanced
  if (checkString.length <= 0) return true;

  for (var i = 0; i < checkString.length; i++) {
    if(checkString[i] === &#39;{&#39;) {
      stack.push(checkString[i]);
    } else if (checkString[i] === &#39;}&#39;) {
      // Pop on an empty array is undefined
      if (stack.length > 0) {
        stack.pop();
      } else {
        return false;
      }
    }
  }

  // If the array is not empty, it is not balanced
  if (stack.pop()) return false;
  return true;
}

재귀

이진 변환

재귀 함수를 통해 입력 숫자를 이진 문자열로 변환:

decimalToBinary(3); // 11
decimalToBinary(8); // 1000
decimalToBinary(1000); // 1111101000

function decimalToBinary(digit) {
  if(digit >= 1) {
    // If digit is not pisible by 2 then recursively return proceeding
    // binary of the digit minus 1, 1 is added for the leftover 1 digit
    if (digit % 2) {
      return decimalToBinary((digit - 1) / 2) + 1;
    } else {
      // Recursively return proceeding binary digits
      return decimalToBinary(digit / 2) + 0;
    }
  } else {
    // Exit condition
    return &#39;&#39;;
  }
}

이진 검색

function recursiveBinarySearch(array, value, leftPosition, rightPosition) {
  // Value DNE
  if (leftPosition > rightPosition) return -1;

  var middlePivot = Math.floor((leftPosition + rightPosition) / 2);
  if (array[middlePivot] === value) {
    return middlePivot;
  } else if (array[middlePivot] > value) {
    return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1);
  } else {
    return recursiveBinarySearch(array, value, middlePivot + 1, rightPosition);
  }
}

숫자

인덱스 값이 2인지 판단

isPowerOfTwo(4); // true
isPowerOfTwo(64); // true
isPowerOfTwo(1); // true
isPowerOfTwo(0); // false
isPowerOfTwo(-1); // false

// For the non-zero case:
function isPowerOfTwo(number) {
  // `&` uses the bitwise n.
  // In the case of number = 4; the expression would be identical to:
  // `return (4 & 3 === 0)`
  // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same
  // spot is 1, then result is 1, else 0. In this case, it would return 000,
  // and thus, 4 satisfies are expression.
  // In turn, if the expression is `return (5 & 4 === 0)`, it would be false
  // since it returns 101 & 100 = 100 (NOT === 0)

  return number & (number - 1) === 0;
}

// For zero-case:
function isPowerOfTwoZeroCase(number) {
  return (number !== 0) && ((number & (number - 1)) === 0);
}

위 내용은 자바스크립트 인터뷰에서 자주 묻는 알고리즘 질문에 대한 자세한 설명입니다. 자세한 내용은 PHP를 참고해주세요. 중국넷(www.php.cn)!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.