面試題:寫演算法,實現陣列中找到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 // 3 n = len(arr) for i in range(n - 2): left_sum = sum(arr[:i+1]) if left_sum > target_sum: continue for j in range(i + 1, n - 1): mid_sum = sum(arr[i+1:j+1]) if mid_sum > target_sum: continue right_sum = total_sum - left_sum - mid_sum if 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))