Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day7

原本應該在30分鐘前就應該來打這篇文章了,但最近又開始政治狂熱了…所以上社群媒體跟人?討論議題XDDD
但打完文章後發現我根本是白癡,我連他是不是行銷帳號(俗稱網軍)都不知道,我在那邊浪費什麼勁啊。
認真覺得所有社群媒體都需要實名制,至少他攻擊我家人跟威脅我時比較好處理XDD
扯遠了,回來LeetCode

Day7: Array Reduce Transformation

問題描述:

Given an integer array nums, a reducer function fn, and an initial value init, return a reduced array.

reduced array is created by applying the following operation: val = fn(init, nums[0])val = fn(val, nums[1])val = fn(val, nums[2])... until every element in the array has been processed. The final value of val is returned.

If the length of the array is 0, it should return init.

Please solve it without using the built-in Array.reduce method.

問題難度:Easy

問題限制:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • 0 <= init <= 1000

我的解題思路

有一個array,經過fn的處理後回傳最終的值。 如果array的長度為0則回傳init

因此我們要先判斷array的長度是否為0:

1
if (nums.length === 0) return init

之後就是把array帶入fn裡面,今天就挑戰自己不要用for 迴圈。

1
2
3
4
5
6
var reduce = function(nums, fn, init) {
if (nums.length === 0) return init
let value = init
nums.forEach(num => {value = fn(value, num)})
return value
};

感覺好像不用第一行也可以XD

其他解法

使用 for…of

1
2
3
4
5
6
7
function reduceArray(nums, fn, init) {
let val = init;
for (const num of nums) {
val = fn(val, num);
}
return val;
}

使用題目禁止的Array.reduce:

1
2
3
var reduce = function(nums, fn, init) {
return nums.reduce((acc, element) => fn(acc, element), init);
};

結語

打完這題時我發現if (nums.length === 0) return init這行好像不是必要的,因為有沒有這行其實都不會影響到最後結果,但我在參考其他人的答案時有看到一則留言,他的説法是説:
如果這個只是程式碼中的一段他會把這行刪掉,但如果這是在面試而且題目有明確指出要回傳,雖然執行結果有體現到這點,但他還是建議保留並用解說的方式告訴面試官你的想法。
我覺得他說的蠻符合我的想法的,因此我保留了它。