LeetCode解答例【JavaScript】(Good率80%以上の良問厳選)※随時更新


LeetCodeのEasyレベルの良問をJavaScriptで解きました。
問題の解き方はここに載せているもの以外にもたくさんあるので、実際に自分で打って確かめてみてください。

LeetCodeはすべて英語ですが、Google翻訳を使うと問題の意図は伝わるくらいに訳してくれます。

問題 461. Hamming Distance

解答例

/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function (x, y) {
  return (x ^ y)
    .toString(2)
    .split("")
    .filter((n) => n == 1).length;
};

問題 557. Reverse Words in a String III

解答例

/**
/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
  return s.split("").reverse().join("").split(" ").reverse().join(" ")
};

問題 771. Jewels and Stones

解答例

/**
 * @param {string} jewels
 * @param {string} stones
 * @return {number}
 */
var numJewelsInStones = function (jewels, stones) {
  // toLowerCace(jewels);
  let sum = 0;
  for (let i = 0; i < stones.length; i++) {
    if (jewels.indexOf(stones[i]) != -1) sum++;
  }

  return sum;
};

問題 905. Sort Array By Parity

解答例

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortArrayByParity = function (A) {
  const temp = [];
  A.forEach((a) => {
    a % 2 == 0 ? temp.unshift(a) : temp.push(a);
  });

  return temp;
};

問題 922. Sort Array By Parity II

解答例

/**
 * @param {string} S
 * @return {string}
 */
var removeDuplicates = function (S) {
  const stack = [];
  for (const char of S) {
    stack[stack.length - 1] == char ? stack.pop() : stack.push(char);
  }
  return stack.join("");
};

問題 977. Squares of a Sorted Array

解答例

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
  return nums.map((a) => a * a).sort((a, b) => a - b);
};

問題 1047. Remove All Adjacent Duplicates In String

解答例

/**
 * @param {string} S
 * @return {string}
 */
var removeDuplicates = function (S) {
  const stack = [];
  for (const char of S) {
    stack[stack.length - 1] == char ? stack.pop() : stack.push(char);
  }
  return stack.join("");
};

問題 1207. Unique Number of Occurrences

解答例

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var uniqueOccurrences = function (arr) {
  let obj = {};

  for (let i = 0; i < arr.length; i++) {
    if (obj[arr[i]] == undefined) {
      obj[arr[i]] = 1;
    } else {
      obj[arr[i]]++;
    }
  }

  return new Set(Object.values(obj)).size === Object.values(obj).length;
};

問題 1337. The K Weakest Rows in a Matrix

解答例

/**
 * @param {number[][]} mat
 * @param {number} k
 * @return {number[]}
 */
var kWeakestRows = function (mat, k) {
  return mat
    .map((value, index) => [index, value.reduce((pre, cur) => pre + cur)])
    .sort((a, b) => a[1] - b[1])
    .slice(0, k)
    .map((pair) => pair[0]);
};

問題 1351. Count Negative Numbers in a Sorted Matrix

回答例

/**
 * @param {number[][]} grid
 * @return {number}
 */

var countNegatives = function (grid) {
  let sum = 0;
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[i].length; j++) {
      if (grid[i][j] < 0) {
        sum++;
      }
    }
  }
  return sum;
};

問題 1356. Sort Integers by The Number of 1 Bits

解答例

/**
 * @param {number[]} arr
 * @return {number[]}
 */
var sortByBits = function (arr) {
  const bitCount = (num) => {
    let sum = 0;
    while (num) {
      sum += num & 1;
      num >>= 1;
    }
    return sum;
  };

  return arr.sort((a, b) => bitCount(a) - bitCount(b) || a - b);
};

問題 1365. How Many Numbers Are Smaller Than the Current Number

解答例

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var smallerNumbersThanCurrent = function (nums) {
  hoge = Array.from(nums).sort((a, b) => b - a);
  let fuga = new Map(hoge.map((num, index) => [num, nums.length - 1 - index]));
  return nums.map((num) => fuga.get(num));
};

問題 1470. Shuffle the Array

解答例

/**
 * @param {number[]} nums
 * @param {number} n
 * @return {number[]}
 */
var shuffle = function (nums, n) {
  for (let i = 0; i < n; i++) {
    nums.push(nums[i], nums[i + n]);
  }
  nums.splice(0, n * 2);
  return nums;
};

問題 1480. Running Sum of 1d Array

解答例

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function (nums) {
  for (let i = 1; i < nums.length; i++) {
    nums[i] += nums[i - 1];
  }
  return nums;
};

問題 1502. Can Make Arithmetic Progression From Sequence

解答例

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var canMakeArithmeticProgression = function (arr) {
  arr.sort((a, b) => a - b);
  for (let i = 1; i < arr.length; i++) {
    if (arr[1] - arr[0] != arr[i] - arr[i - 1]) {
      return false;
    }
  }
  return true;
};

問題 1512. Number of Good Pairs

解答例

/**
 * @param {number[]} nums
 * @return {number}
 */
var numIdenticalPairs = function (nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] == nums[j]) sum++;
    }
  }
  return sum;
};

問題 1678. Goal Parser Interpretation

解答例

/**
 * @param {string} command
 * @return {string}
 */
var interpret = function (command) {
  return command.split("()").join("o").split("(al)").join("al");
};

問題 1700. Number of Students Unable to Eat Lunch

解答例

/**
 * @param {number[]} students
 * @param {number[]} sandwiches
 * @return {number}
 */
var countStudents = function (students, sandwiches) {
  while (students.length > 0 && students.indexOf(sandwiches[0]) != -1) {
    if (students[0] == sandwiches[0]) {
      students.shift();
      sandwiches.shift();
    } else {
      students.push(students.shift());
    }
  }
  return students.length;
};