簡單記錄在LeetCode刷題時遇到的問題及思考過程~
[題目]
You are given an
m x n
integer gridaccounts
whereaccounts[i][j]
is the amount of money theith
customer has in thejth
bank. Return the wealth that the richest customer has.A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
Following Examples:
Input: accounts = [ [1,5], [7,3],[3,5] ]
Output: 10
Explanation:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
[解題]
本人使用的方法1
- 題目解讀:從給定的accounts陣列中,將其中各別的子陣列獨自相加成值後做比大小,並返回最大值的值。
- 思考過程:
a. 陣列裡的所有子陣列都要做計算,而且計算完要形成新的陣(因為要將計算結果做比大小) → 使用map()對每個子陣列做遍歷。
b. 要將子陣列裡的每個數字作累計相加 → 使用reduce() 作為累加器。
c. 當所有子陣列裡的數字都計算完成後,得到的是一個新陣列:裡面的值是每個子陣列的總和,因為後續要作數值比大小,所以要將它存在一新變數 → 將 a,b兩項的程式碼賦值給新變數 subTotal。
d. 把subTotal這個新陣列裡的值拿去做比大小 → 使用Math.max() ,但因為subTotal此變數是陣列,所以要將其轉變成Math.max()可以作用的對象,在此使用展開運算子 “…” 將subTotal展開成引數傳入。
e. 最後得到Math.max() 作用完畢的值,存進一變數max並回傳結果 → return max。 - code:如下,提交後leetCode網站上顯示綠色的Accepted、通過啦!
//先把陣列裡的陣列各別的值先相加,再把各別的值作比較,最終產出最大的值
//使用 map 方法對每個子陣列進行遍歷,並使用 reduce 方法將子陣列的值相加
var maximumWealth = function (accounts) {
let subTotal = accounts.map((subArr) => {
return subArr.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
});
let max = Math.max(...subTotal);
return max;
};
console.log(
maximumWealth([
[1, 2, 3],
[3, 2, 1],
])
); //6
console.log(
maximumWealth([
[1, 5],
[7, 3],
[3, 5],
])
); //10
方法2:優化方法1的程式碼,寫成一行
var maximumWealth = (accounts) =>
Math.max(
...accounts.map((item) => item.reduce((acc, num) => (acc += num), 0))
);
方法3:使用巢狀迴圈
var maximumWealth = function (accounts) {
var res = 0;
for (var i = 0; i < accounts.length; i++) {
var temp = 0;
for (var j = 0; j < accounts[i].length; j++) {
temp += accounts[i][j];
}
res = Math.max(res, temp);
}
return res;
};
// provided by zeldox
此題算是array方法的經典題吧,是時候考驗你的array基礎啦~上述提供幾種方法解題,適時綜合使用array方法,讓你的程式碼更加簡潔!