码迷,mamicode.com
首页 > 其他好文 > 详细

(Easy) Partition Array Into Three Parts With Equal Sum - LeetCode

时间:2019-09-05 18:12:35      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:exe   xpl   Plan   ret   esc   bsp   turn   ons   pre   

Description:

Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.

Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])

 

Example 1:

Input: [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:

Input: [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

 

Note:

  1. 3 <= A.length <= 50000
  2. -10000 <= A[i] <= 10000
Accepted
18,270
Submissions
32,514

Solution:

class Solution {
    public boolean canThreePartsEqualSum(int[] A) {
        
        // int Sum of each part 
        int sum = 0;
        
        for(int i = 0; i< A.length; i++){
            
            sum = sum + A[i];    
        }
        
        sum = sum / 3; 
        
        
        int find_i =-1;
        int find_j = -1;
        int cur_sum = 0;
        for(int i = 0; i< A.length; i++){
            
            cur_sum = cur_sum +A[i];
            
            if(cur_sum == sum){
                
                find_i = i;
             
                cur_sum = 0;
                break;
            }
        }
        
        for(int k = find_i+1; k<A.length; k++){
            cur_sum = cur_sum+A[k];
            
            if(cur_sum ==sum){
                
                find_j = k;
                break;
            }
            
            
        }
    
       if(find_i <find_j && find_i>=0&& find_j <A.length){
           return true;
       }
      return false;
    }
}

 

(Easy) Partition Array Into Three Parts With Equal Sum - LeetCode

标签:exe   xpl   Plan   ret   esc   bsp   turn   ons   pre   

原文地址:https://www.cnblogs.com/codingyangmao/p/11468713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!