comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
简单 |
1378 |
第 129 场周赛 Q1 |
|
给你一个整数数组 arr
,只有可以将其划分为三个和相等的 非空 部分时才返回 true
,否则返回 false
。
形式上,如果可以找出索引 i + 1 < j
且满足 (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])
就可以将数组三等分。
示例 1:
输入:arr = [0,2,1,-6,6,-7,9,1,2,0,1] 输出:true 解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
示例 2:
输入:arr = [0,2,1,-6,6,7,9,-1,2,0,1] 输出:false
示例 3:
输入:arr = [3,3,6,5,-2,2,5,1,-9,4] 输出:true 解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
提示:
3 <= arr.length <= 5 * 104
-104 <= arr[i] <= 104
我们先求出整个数组的和,然后判断和是否能被 3 整除,如果不能,直接返回
否则,我们记
然后我们遍历数组,对于每个元素
最后判断
时间复杂度
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
s, mod = divmod(sum(arr), 3)
if mod:
return False
cnt = t = 0
for x in arr:
t += x
if t == s:
cnt += 1
t = 0
return cnt >= 3
class Solution {
public boolean canThreePartsEqualSum(int[] arr) {
int s = Arrays.stream(arr).sum();
if (s % 3 != 0) {
return false;
}
s /= 3;
int cnt = 0, t = 0;
for (int x : arr) {
t += x;
if (t == s) {
cnt++;
t = 0;
}
}
return cnt >= 3;
}
}
class Solution {
public:
bool canThreePartsEqualSum(vector<int>& arr) {
int s = accumulate(arr.begin(), arr.end(), 0);
if (s % 3) {
return false;
}
s /= 3;
int cnt = 0, t = 0;
for (int x : arr) {
t += x;
if (t == s) {
t = 0;
cnt++;
}
}
return cnt >= 3;
}
};
func canThreePartsEqualSum(arr []int) bool {
s := 0
for _, x := range arr {
s += x
}
if s%3 != 0 {
return false
}
s /= 3
cnt, t := 0, 0
for _, x := range arr {
t += x
if t == s {
cnt++
t = 0
}
}
return cnt >= 3
}
function canThreePartsEqualSum(arr: number[]): boolean {
let s = arr.reduce((a, b) => a + b);
if (s % 3) {
return false;
}
s = (s / 3) | 0;
let [cnt, t] = [0, 0];
for (const x of arr) {
t += x;
if (t == s) {
cnt++;
t = 0;
}
}
return cnt >= 3;
}
impl Solution {
pub fn can_three_parts_equal_sum(arr: Vec<i32>) -> bool {
let sum: i32 = arr.iter().sum();
let s = sum / 3;
let mod_val = sum % 3;
if mod_val != 0 {
return false;
}
let mut cnt = 0;
let mut t = 0;
for &x in &arr {
t += x;
if t == s {
cnt += 1;
t = 0;
}
}
cnt >= 3
}
}