Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 81c5068

Browse files
🐱(array): 1013. 将数组分成和相等的三个部分
1 parent 081c0c5 commit 81c5068

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎docs/data-structure/array/README.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2663,4 +2663,49 @@ class Solution(object):
26632663
return tmp_string
26642664
```
26652665

2666+
## 1013. 将数组分成和相等的三个部分
26662667

2668+
[原题链接](https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum/)
2669+
2670+
### 思路
2671+
2672+
1. 数组求和,看是否可以整除三,不能整除则直接返回 `false`
2673+
2. 双指针指向数组前后,前后都分别开始找累加和等于目标值的部分,如果前后都能找到,则中间的自动就找到了
2674+
2675+
注意问题:
2676+
2677+
1. 存在 `[1,-1,1,-1]` 这样的用例,需要判断双指针最终位置,相距是否大于 1,即中间是否还有位置
2678+
2. 目标值可以为 0,所以左右区间的数据应当初始化为 `A[0]``A[length - 1]`
2679+
2680+
```python
2681+
class Solution:
2682+
def canThreePartsEqualSum(self, A: List[int]) -> bool:
2683+
# 求总和
2684+
s = sum(A)
2685+
if s % 3 != 0:
2686+
return False
2687+
part = s // 3
2688+
2689+
# 双指针
2690+
i = 0
2691+
j = len(A) - 1
2692+
# 计算左右区间和
2693+
left_part = A[i]
2694+
right_part = A[j]
2695+
res = False
2696+
while i < j:
2697+
if left_part != part:
2698+
i += 1
2699+
left_part += A[i]
2700+
2701+
if right_part != part:
2702+
j -= 1
2703+
right_part += A[j]
2704+
2705+
if left_part == part and right_part == part:
2706+
res = True
2707+
break
2708+
# print(i, j)
2709+
# 处理特殊情况:[1,-1,1,-1]
2710+
return res and j - i > 1
2711+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /