zoukankan      html  css  js  c++  java
  • 1013. Partition Array Into Three Parts With Equal Sum

    问题:

    给定数组,如果刚好将数组分成三段,使得每一段的和相等,则返回true,否则返回false

    Example 1:
    Input: A = [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: A = [0,2,1,-6,6,7,9,-1,2,0,1]
    Output: false
    
    Example 3:
    Input: A = [3,3,6,5,-2,2,5,1,-9,4]
    Output: true
    Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
     
    Constraints:
    3 <= A.length <= 50000
    -10^4 <= A[i] <= 10^4
    

      

      

    解法:

    首先求数组和sum

    然后遍历数组,累加tmp

    如果tmp*3==sum,那么到目前的元素,可划分为一组,同时清空tmp=0,计数组数cout++

    如果cout>=3后,不再清空tmp

    遍历完毕数组后,如果tmp==0且cout==3,满足题意返回true。

    如果tmp!=0或者cout!=3

    那么,最后一组不能满足=sum/3整除的条件,

    或是分组不够3组。则需要返回false。

    代码参考:

     1 class Solution {
     2 public:
     3     bool canThreePartsEqualSum(vector<int>& A) {
     4         int sum=0, tmp=0, cout=0;
     5         for(int a:A) sum+=a;
     6         for(int a:A){
     7             tmp+=a;
     8             if(tmp*3==sum && cout<3){
     9                 tmp=0;
    10                 cout++;
    11             }
    12         }
    13         return tmp==0 && cout==3;
    14     }
    15 };
  • 相关阅读:
    JavaScript OOP 思想
    单页界面和 AJAX 模式
    jQuery 的 ready 函数是如何工作的?
    Dojo系列教程
    谈谈javascript语法里一些难点问题(一)
    2014年总结、2015年的小计划--女生程序员小感想
    Android名词解释
    【JS】defer / async
    关于对defer的理解.
    defer和async的区别
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13112085.html
Copyright © 2011-2022 走看看