今天是我們最後一天的leetcode刷題,直接上今天的題目:
/*
Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])
Example 1:
Input: A = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
Example 2:
Input: A = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: A = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
*/
var canThreePartsEqualSum = function(A) {
};
今天的題目會給一個數字陣列,去檢測這個陣列分成三份之後(每一份數量不需相等),每一份的數值相加會不會互相相等,如果有回傳true,沒有false。
思考:
var canThreePartsEqualSum = function(A) {
total = A.reduce((sum, num)=>{return sum + num})
average = total/3
};
var canThreePartsEqualSum = function(A) {
total = A.reduce((sum, num)=>{return sum + num})
average = total/3
let num = 0
let result = []
};
var canThreePartsEqualSum = function(A) {
total = A.reduce((sum, num)=>{return sum + num})
average = total/3
let num = 0
let result = []
for(let i = 0; i<A.length; i++){
num += A[i]
if (num == average){
result.push(num)
num = 0
}
if(i === A.length-1 && num !== 0){
result.push(num)
}
}
return result[0] === result[1] && result[1] === result[2]
};
以上就是今天的挑戰,那一個禮拜的leetcode刷題就到這邊,如果有哪位大大路過經過,還請多多分享賜教。明天開始就進入我們的todolist實作。