面试题:写算法,实现数组中找到2个点分割数组,使得三部分数组元素的和相等的方法,备注:求和不包括这两个点
Python实现:
def find_tripartition(arr):total_sum = sum(arr)if total_sum % 3 != 0:return "No solution, as the sum of elements cannot be divided by 3 evenly."target_sum = total_sum // 3n = len(arr)for i in range(n - 2):left_sum = sum(arr[:i+1])if left_sum > target_sum:continuefor j in range(i + 1, n - 1):mid_sum = sum(arr[i+1:j+1])if mid_sum > target_sum:continueright_sum = total_sum - left_sum - mid_sumif right_sum == target_sum:return (i, j)return "No valid tripartition found."#arr = [1, 2, 0, 0, 3, 0, 2, 1] [3, 0, 3, 0, 3, 0, 0, 3]print(find_tripartition(arr))