Try   HackMD

Leetcode 練習筆記

30 Days of LC JavaScript Challenge

Day30

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day

Day12

Day11

Day10

Input:
fn = function sum(a, b, c) { return a + b + c; }
inputs = [[1,2],[3]]
Output: 6
Explanation:
curriedSum(1, 2)(3) should return the same value as sum(1, 2, 3).

var curry = function(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            // 如果傳入的參數數量已達到原函式所需的參數數量,則直接執行原函式
            return fn(...args);
        } else {
            // 如果傳入的參數數量不足,則返回一個新的柯里化函式,等待更多的參數傳入
            return function(...moreArgs) {
                return curried(...args.concat(moreArgs));
            };
        }
    };
};

// 測試
function sum(a, b, c) {
    return a + b + c;
}

const curriedSum = curry(sum);
console.log(curriedSum()(1, 2, 3)); // 6
console.log(curriedSum(1)(2)(3)); // 6
console.log(curriedSum(1, 2)(3)); // 6
console.log(curriedSum(1)(2, 3)); // 6

Day9 Memoize

Input
"sum"
["call","call","getCallCount","call","getCallCount"]
[[2,2],[2,2],[],[1,2],[]]
Output
[4,4,1,3,2]
Explanation
const sum = (a, b) => a + b;
const memoizedSum = memoize(sum);
memoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.
memoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.
// Total call count: 1
memoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.
// Total call count: 2

function memoize(fn) {
  const cache = {};//用一個物件來儲存 放入的input跟結果 
  return function (...args) {
    const key = JSON.stringify(args); 由於物件的key只能是string所以必須透過stringify來讓args這個array變成可以儲存的key
    if (key in cache) { 
      return cache[key];
    }
    const functionOutput = fn(...args);
    cache[key] = functionOutput;
    return functionOutput;
  };
}

Day8 Allow One Function Call

Input: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]
Output: [{"calls":1,"value":140}]
Explanation:
const onceFn = once(fn);
onceFn(5, 7, 4); // 140
onceFn(2, 3, 6); // undefined, fn was not called
onceFn(4, 6, 8); // undefined, fn was not called

var once = function(fn) {
     let hasBeenCalled = false;
    return function(...args){
 if (hasBeenCalled) {
      return undefined;
    } else {
      hasBeenCalled = true;
      return fn(...args);
    }
    }
};

Day7 Function Composition

Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
Output: 65
Explanation:
Evaluating from right to left
Starting with x = 4.
2 * (4) = 8
(8) * (8) = 64
(64) + 1 = 65

var compose = function(functions) {
	return function(x) {
        let result=x;
        for(let i=functions.length-1;i>=0;i--){
            result=functions[i](result);
        }
        return result;
    }
};

Day6 Array Reduce Transformation

Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130
Explanation:
initially, the value is init=100.
(100) + nums[0]^2 = 101
(101) + nums[1]^2 = 105
(105) + nums[2]^2 = 114
(114) + nums[3]^2 = 130
The final answer is 130.

var reduce = function(nums, fn, init) {
    let result=init;
    for(let i=0;i<nums.length;i++){
        result=fn(result,nums[i])
    }
    return result;
};

Day5 Filter Elements from Array

Example 1:
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
Explanation:
const newArray = filter(arr, fn); // [20, 30]
The function filters out values that are not greater than 10
Example 2:
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
Explanation:
fn can also accept the index of each element
In this case, the function removes elements not at index 0

var filter = function(arr, fn) {
  const result=[];
for(let i=0;i<arr.length;i++){
if (fn(arr[i],i)){
  result.push(arr[i])
}
}
return result;
};

Day4 Apply Transform Over Each Element in Array

Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.

var map = function(arr, fn) {
    return arr.map((item,i)=>fn(item,i));
};

Day3 Counter II(closure)

Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
Output: [1,2,1,0,0]
Explanation:
const counter = createCounter(0);
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
counter.reset(); // 0
counter.reset(); // 0

var createCounter = function(init) {
  let currentCount = init;

  function increment() {
    return ++currentCount;
  }

  function decrement() {
        currentCount -= 1;
       return currentCount;
  }

  function reset() {
      return (currentCount = init);
  }

  return { increment, decrement, reset };
};

Day2 Counter(closure)

Input:
n = -2
["call","call","call","call","call"]
Output: [-2,-1,0,1,2]
Explanation: counter() initially returns -2. Then increases after each sebsequent call.

var createCounter = function(n) {
    let input=n-1;
    return function() {
        input++;
        return input;
    };
};

Day1 Create Hello World Function(closure)

var createHelloWorld = function() {
    return function(...args) {
        return "Hello World"
    }
};
  1. question:

Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As shown, "codeleet" becomes "leetcode" after shuffling.

var restoreString = function(s, indices) {
  let shuffled = new Array(s.length);
  for (let i = 0; i < indices.length; i++) {
    shuffled[indices[i]] = s.charAt(i);
  }
  return shuffled.join('');
};
//let arr = new Array(); // -> [] 給arr長度但內容仍然是空的
//[ <8 empty items> ]
//charAt() 方法从一个字符串中返回指定的字符。
  1. Deci-Binary Numbers

Example 1:
Input: n = "32"
Output: 3
Explanation: 10 + 11 + 11 = 32

Example 2:
Input: n = "82734"
Output: 8
82734-11111-11111-10111-10101-10100-10100-10100-10000
==>要做八次才能使得82734變成00000

Example 3:
Input: n = "27346209830709182346"
Output: 9

(換言之就是找到最大的數字)

var minPartitions = function(n) {
    const nArr=n.split('');
    const numArr=nArr.map(s=>parseInt(s));
    return Math.max(...numArr);
};
  1. Reduce

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);

  1. Question

Input: nums = [10,4,8,3]
Output: [15,1,11,22]
Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].
The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].

var leftRigthDifference = function(nums) {
const n = nums.length;
const leftSum = Array(n).fill(0);
const rightSum = Array(n).fill(0);
for (let i = 1; i < n; i++) {
leftSum[i] = leftSum[i-1] + nums[i-1];
rightSum[n-i-1] = rightSum[n-i] + nums[n-i];
}
return nums.map((num, i) => Math.abs(leftSum[i] - rightSum[i]));
};