当前位置: 代码迷 >> 综合 >> leetcode-Algorithms-1013|将数组分成和相等的三个部分
  详细解决方案

leetcode-Algorithms-1013|将数组分成和相等的三个部分

热度:64   发布时间:2023-12-12 12:06:01.0

原题

给你一个整数数组 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来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

双指针

代码

package leetcode.Algorithms;public class Solution_1013 {
    public static void main(String[] args) {
    //[14,6,-10,2,18,-7,-4,11]//[3,3,6,5,-2,2,5,1,-9,4]//[1,-1,1,-1]//[3,3,6,5,-2,2,5,1,-9,4]int[] arr = {
    3,3,6,5,-2,2,5,1,-9,4};System.out.println(canThreePartsEqualSum(arr));}public static boolean canThreePartsEqualSum(int[] arr) {
    boolean RE = false;int sum = 0;for (int i : arr) {
    sum += i;}if (sum % 3 != 0) {
    return RE;} else {
    int target = sum / 3;int left = 0;int right = arr.length-1;Boolean l = false;Boolean r = false;while (left + 1 < right) {
    int sumleft = 0;int sumright = 0;if (l == false) {
    for (int i = 0; i <= left; i++) {
    sumleft += arr[i];}if (sumleft == target) {
    l = true;}else {
    left++;}}if (r == false) {
    for (int i = right; i <arr.length; i++) {
    sumright += arr[i];}if (sumright == target) {
    r = true;}else {
    right--;}}if (l == true && r == true) {
    RE = true;break;}}return RE;}}
}